Rails' Flash: Now for Django
For those unfamiliar to Rails, flash is a message passing system from one page to the next. In Django, there is User.message_set.create(), but that only works for logged-in users and is a bit cumbersome.
While I’ve been loving Django, I’ve missed the ease of doing flash[:message] = ‘It has been saved”
So, I made it for Django:
class FlashMiddleware:
> def process_response(self, request, response):
>> try:
>>> request.session[‘flash’] = request.flash
>> except:
>>> pass
>> return response
def flash(request):
> if ‘flash’ in request.session:
>> flash = request.session[‘flash’]
>> del request.session[‘flash’]
>> return {‘flash’: flash}
> return {‘flash’: None}
You have to add the middleware and context processor to the settings.py file, but it works nicely and now you have message passing abilities without the issue of having a user logged in.
This whole thing did illustrate a big difference between Rails and Django. In Rails, you can declare an instance variable (@varname) pretty much anywhere and have it get into the global scope – for example, instance variables are automatically added to the template context rather than having to specify which variables should be available to the template. Django, on the other hand, likes you to pass things along that you want passed along. This is probably better practice, but it meant having to implement flash differently.
I latched onto using the request object to store the flash because it was the only thing I could count on to be in all of my views.
Now, in a view, just type:
request.flash = ‘Your message here’
Anyway, I hope you like it/find it useful.