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>
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.
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' ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With