Django middleware process_template_response setup

1.1k views Asked by At

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>
1

There are 1 answers

7
Gocht On BEST ANSWER

I have work in something like this before, I think you should use the context_data response's attribute:

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

Then you need register this class in MIDDLEWARE_CLASSES tuple in your settings file:

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

The example above assumes you have a middleware folder inside your application named 'yourapp'.

Finally you should be able to use {{ count }} in template.