I would like to create a function that checks if the user has any notifications. If they do, the number should be displayed in the navbar.
Could someone please help me refactor this to do just that?
Thank you!
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>
I have work in something like this before, I think you should use the
context_data
response's attribute:Then you need register this class in
MIDDLEWARE_CLASSES
tuple in yoursettings
file:The example above assumes you have a
middleware
folder inside your application named 'yourapp'.Finally you should be able to use
{{ count }}
in template.