gpt4 book ai didi

python - Django 中间件 process_template_response 设置

转载 作者:太空宇宙 更新时间:2023-11-04 05:49:07 25 4
gpt4 key购买 nike

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

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

谢谢!

中间件.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 }}

关于python - Django 中间件 process_template_response 设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31060110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com