Wednesday, February 14, 2007

Moving from Rails to Django: Replacing flash[:notice]

One of the most common practices I came across while learning Rails is the flash[:notice] mechanism used to send (error) messages to the template. Consequently it was also one of my first targets to migrate when I started moving a pet application from Rails to Django.

I came up with a simple (and all too obvious) way to send error messages to the template. I am sure that there are better ways to do this. If you know of any, please take a minute to share them.

First, the Rails snippet. Next, the equivalent in Django. The template in Rails ... ... and the template in Django. While testing in Django, flash can be treated just like any other context variable.


Ian said...

Unfortunately, flash in Rails works not only for forwards to the template, but also across a 302 redirect.

Anonymous said...

You are probably much happier with
request.user.message_set.create(message='Your Message goes here')

Manoj Govindan said...

Thanks. I will remember to use user.message_set in the future.

lorien said...

There is a better way.
You can place you messages in session.
For example, request.session['message']
Then in templates just get it from request.session.message
You'll have to use middleware which will empty request.session['message'] in the beginning of all requests.
If you want to set message for the next page after redirect then you can use request.session['next_message'] and special middleware which will convert 'next_mesage' to 'message' in the beginning of all requests.