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:


sriram said...

He hee :) Manoj, good to see you as the resident web expert! Here is a question. When I clicked on the book images posted by ravi in his blog, I was shown the full image with a very strange looking link on ( I tried looking up Non-existant. Would you care to explain more about those links?

Manoj Govindan said...

Me, an expert? Bwahaha :P :P

I am not sure what exactly is happening. I'd venture a guess that the URL that you see on the address bar is created on the fly at the time of uploading the image and mapped to something else behind the scenes. Apparently the *exact* link matches some pattern where as combinations of the individual parts do not.

Btw did you notice that this link as well as this one point to the same book?

Anonymous said...

Manoj, absolutely brilliant! really!

And for the people who want a more django-admin-like message. You can use these CSS directives:

#messages {
/* div position and layout */
#messages ul {
/* padding etc. for the list */
#messages ul li {
/* and some color and layout stuff */

/* only left the color tag for readability */
#messages ul li.m0 { color: green; }
#messages ul li.m1 { color: yellow; }
#messages ul li.m2 { color: red; }

Happy coding!