【发布时间】:2015-06-25 20:24:48
【问题描述】:
我想创建一个函数来检查用户是否有任何通知。如果是,则该数字应显示在导航栏中。
有人可以帮我重构一下吗?
谢谢!
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>
【问题讨论】:
-
为什么要在中间件中这样做?这是模板标签的工作。
-
@DanielRoseman 你能解释一下怎么做吗?
标签: python django django-templates django-middleware