Django 中间件 process_template_response 安装

Django middleware process_template_response setup

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

有人可以帮我重构这个来做到这一点吗?

谢谢!

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>

我以前做过类似的工作,我认为你应该使用 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

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

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

以上示例假设您的应用程序中有一个名为 'yourapp'.

middleware 文件夹

您终于可以在模板中使用 {{ count }}