开发者

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 }})&l开发者_运维问答t;/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' ]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜