user.message_set
instead to pass messages. This mechanism makes use of Django's message model and is easy to use. However it does have a limitation. Messages cannot be assigned types - say, 'Error' or 'Success' or 'Warning'. This has been discussed at some length at the Django site. A design decision is awaited as the suggested changes will not be backward compatible.
In the meantime I needed message types for a pet application and came up with a quick and dirty way of providing some. Changes were required in three places: the view, where messages are created; the template which displays the messages and the style sheet used for styling the rendered templates.
The solution (did I say it was dirty?) involved prefixing a digit and a separator to all messages. The digit would indicate the type of message. I chose 0 to indicate success, 1 for warnings, 2 for errors etc. Corresponding styles were then created to appropriately style the messages.
Here is a sample view:
- def save_something(request):
- if saved:
- request.user.message_set.create(message = "0|Object was saved successfully")
- else:
- request.user.message_set.create(message = "2|Object could not be saved")
- {% if messages %}
- <div id="messages">
- {% for message in messages %}
- <p class="m{{ message|slice:"0:1"}}">{{ message|slice:"2:" }}</p>
- {% endfor %}
- </div>
- {% endif %}
- #messages p {
- margin: 0; padding: 0;
- }
- #messages p.m0 {
- background: transparent url(success.gif) 0 100% no-repeat;
- color: green;
- }
- #messages p.m1 {
- background: transparent url(warning.gif) 0 100% no-repeat;
- color: yellow;
- }
- #messages p.m2 {
- background: transparent url(failure.gif) 0 100% no-repeat;
- color: red;
- }
- /* etc */