cloudzhou
cloudzhou

Reputation: 101

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>

Upvotes: 7

Views: 3217

Answers (2)

Maxim Razin
Maxim Razin

Reputation: 9466

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' ]

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599600

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.

Upvotes: 5

Related Questions