Django session message via middleware
Django session message is a wonderful app in django to provide messages for the users. http://code.google.com/p/django-session-messages/
It is used to provide system wide announcements and user specific messages for both Authenticated and Anonymous users in a django system.
The app works via the context processors. This is means, it is very easy to integrate with your application.
But for us at taggle, we had issues when we deployed our view caches. It created odd behaviors resulting in wrong messages posted to wrong people and some messages not getting posted as the pages got cached on the server. To get around this we decided to pass the session messages via cookies and then read it via javascript at the user end and then display it.
Here is the middleware which puts the session message in the cookies, and the front end javascript takes care of the rest.
from django.conf import settings
from django.utils.encoding import smart_str
import urllib
class SessionMessageMiddleware(object):
def process_response(self, request, response):
"""
Sticks the session_messages into the cookies for the current session.
Each message is seperated by ###.
"""
try:
domain = settings.COOKIE_DOMAIN_NAME
except AttributeError:
domain = None
session_messages = LazyMessages(request)
s_message = ""
if 'session_messages' in request.COOKIES:
if len(request.COOKIES['session_messages']) == 0:
for m in session_messages:
s_message += urllib.quote(smart_str(m)) + "###"
else:
s_message = request.COOKIES['session_messages']
else:
for m in session_messages:
s_message += urllib.quote(smart_str(m)) + "###"
if domain != None:
response.set_cookie("session_messages",s_message,domain=settings.COOKIE_DOMAIN_NAME)
response.set_cookie("session_gaevents",s_gmessage,domain=settings.COOKIE_DOMAIN_NAME)
response.set_cookie("session_mids",s_mids,domain=settings.COOKIE_DOMAIN_NAME)
else:
response.set_cookie("session_messages",s_message)
response.set_cookie("session_gaevents",s_gmessage)
response.set_cookie("session_mids",s_mids)
return response
At the front end we use jQuery to dismantle the cookie and then display it. Here is the small snippet we use.
function showSessionMessages(){
try{
s_msg=$.cookie("session_messages");
$.cookie("session_messages", null, { path : '/', expires: -5});
if ( s_msg != null){
s_msg = s_msg.replace(/^"/,"").replace(/"$/,"");
s_msg = s_msg.replace(/###$/,"");
msgs=s_msg.split("###");
msgs=unique(msgs);
if (msgs.length > 0 && msgs[0].length > 0){
$.each(msgs, function(i,l){
show_message(l);
});
}
}
}
catch(err){}
}








