Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django middleware set user special global variable

if every web page has a user new message notice(new message count, like message(1)), how can i pass variable '{ new_message_count: 1}' to every view i want to using middleware:

class page_variable():
def process_request(self, request):
    # put the variable to the request or response so can used in template variable
    return None

and template look like:

<a href="/message/">new <em>({{ new_message_count }})</em></a>
like image 373
cloudzhou Avatar asked Nov 14 '10 15:11

cloudzhou


2 Answers

There's already a built-in messaging framework that handles all of this for you.

However, assuming you really want to roll your own, you can't pass things into the context from middleware. You can attach it to the request object, which you can then use in your view or template, or add a context processor which takes the variable from the request and adds it into the context.

like image 141
Daniel Roseman Avatar answered Sep 24 '22 01:09

Daniel Roseman


In the development version of django, you can edit template context from a middleware before rendering:

class MessageCountMiddleware:
    def process_template_response(self, request, response):
        response.context['new_message_count'] = message_count(request.user)

In Django 1.2 you can create a custom context processor:

def add_message_count(request):
    return { 'new_message_count': message_count(request.user) }

and register it in settings

TEMPLATE_CONTEXT_PROCESSORS += [ 'my_project.content_processors.add_message_count' ]
like image 26
grep Avatar answered Sep 23 '22 01:09

grep