Django middleware sets a custom global variable

if each web page has a notification of a new user (new number of messages, for example message (1)), how can I pass the variable '{new_message_count: 1}' for each view I want to use 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 the template is as follows:

 <a href="/message/">new <em>({{ new_message_count }})</em></a> 
+7
variables django templates middleware response
source share
2 answers

You already have an integrated messaging infrastructure that handles all this for you.

However, assuming you really want to collapse your own, you cannot pass things into 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 that takes a variable from the request and adds it to the context.

+5
source share

In the django development version, you can edit the template context from the middle layer 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 your own context handler:

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

and register it in the settings

 TEMPLATE_CONTEXT_PROCESSORS += [ 'my_project.content_processors.add_message_count' ] 
+3
source share

All Articles