Thursday, November 15, 2007

Quick and dirty 'type' for Django's message model

In an earlier post I had mentioned using a 'flash' variable passed to templates as a mechanism for passing messages to users. Following an anonymous tip I started using 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: The template looks something like this: There is a corresponding style sheet as well: