Skip to main content
 首页 » 编程设计

python之Django 中间件 process_template_response 设置

2025年05月04日39zfyouxi

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

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

谢谢!

中间件.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 元组中注册这个类:

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

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

最后,您应该能够在模板中使用 {{ count }}。