Django中间件process_template_response设置

时间:2015-06-25 20:24:49

标签: python django django-templates django-middleware

我想创建一个检查用户是否有任何通知的函数。如果有,则该数字应显示在导航栏中。

有人可以帮助我重构这个吗?

谢谢!

middleware.py:

def process_template_response(self, request, response):
    if request.user.is_authenticated():
        try:
            notifications = Notification.objects.all_for_user(request.user).unread()
            count = notifications.count()
            context = {
                "count": count
            }
            response = TemplateResponse(request, 'navbar.html', context)
            return response
        except:
            pass
    else:
        pass

navbar.html:

<li >
    <a href="{% url 'notifications_all' %}">
        {% if count > 0 %}Notifications ({{ count }}){% else %}Notifications{% endif %}
    </a>
</li>

1 个答案:

答案 0 :(得分:1)

我之前有类似的工作,我认为你应该使用context_data响应的属性:

class NotificationMiddleware(object):
    def process_template_response(self, request, response):
        if request.user.is_authenticated():
            try:
                notifications = Notification.objects.all_for_user(request.user).unread()
                count = notifications.count()
                response.context_data['count'] = count  # I recomend you to use other name instead of 'count'
                return response
            except Exception, e:
                print e  # Fix possible errors
                return response
        else:
            return response

然后,您需要在MIDDLEWARE_CLASSES文件的settings元组中注册此课程:

# settings.py
MIDDLEWARE_CLASSES = (
    # Django middlewares
    ....
    'yourapp.middleware.NotificationMiddleware',
)

上面的示例假设您的应用程序中有一个名为“yourapp”的middleware文件夹。

最后,您应该可以在模板中使用{{ count }}