How to send a session message to an anonymous user on a Django site?

I often display user activity messages to log in to my users in Django app views using:

request.user.message_set.create("message to user") 

How can I do the same for anonymous (not logged in) users? There is no request.user for anonymous users, but the Django documentation says that using the "middleware" middleware, you can do the same thing as the above code. The Django documentation, which refers to the session middleware, claims this is possible, but I could not find how to do this from the session documentation.

+6
python django django-views session
source share
3 answers

See http://code.google.com/p/django-session-messages/ until a patch that allows session-based messages gets into the Django tree (as I saw recently, it is marked as 1.2, so there is no hope for quick add ...).

Another project with similar functionality is Django Flash ( http://djangoflash.destaquenet.com/ ).

+4
source share

This is what I do using context processors:

project/application/context.py (check messages and add them to context):

 def messages(request): messages = {} if 'message' in request.session: message_type = request.session.get('message_type', 'error') messages = {'message': request.session['message'], 'message_type': message_type} del request.session['message'] if 'message_type' in request.session: del request.session['message_type'] return messages 

project/settings.py (add context to TEMPLATE_CONTEXT_PROCESSORS ):

 TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.request", "django.core.context_processors.debug", "django.core.context_processors.media", "django.core.context_processors.auth", "project.application.context.messages", ) 

In this case, the messages function will be called upon each request and everything that it returns will be added to the template context. If necessary, if I want to give the user a message, I can do this:

 def my_view(request): if someCondition: request.session['message'] = 'Some Error Message' 

Finally, in the template, you can simply check if there are errors to display:

 {% if message %} <div id="system_message" class="{{ message_type }}"> {{ message }} </div> {% endif %} 

The type of message is used only in style, depending on what it is ("error", "notification", "success") and the configuration method, which you can add only 1 message at a time for the user, but that’s all I really need needed so this works for me. It can be easily changed to allow multiple messages, etc.

+7
source share

Store the data directly in a session that is similar to a dict object. Then in the view / template check the value.

Further information here:

http://docs.djangoproject.com/en/dev/topics/http/sessions/#using-sessions-in-views

You can also create a middleware class to check the session object for each request and create your own structure there.

+4
source share

All Articles