2

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>
jape
  • 2,861
  • 2
  • 26
  • 58

1 Answers1

1

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.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Gocht
  • 9,924
  • 3
  • 42
  • 81
  • Thank you! How would I show which template this is for? – jape Jun 25 '15 at 21:03
  • This will process all requests, so you can use `{{ count }}` in every template. – Gocht Jun 25 '15 at 21:06
  • Unfortunately, it's not working for me. It doesn't seem as if anything is coming through – jape Jun 25 '15 at 21:15
  • Have you register it in `MIDDLEWARE_CLASSES` in your settings file? – Gocht Jun 25 '15 at 21:18
  • I just updated the answer. I made a mistake it is `context_data` instead of `context` – Gocht Jun 25 '15 at 21:27
  • Can you trace it, insert `import pdb; pdb.set_trace()` and be sure the query and everything is right, be sure no error is triggered, test every line. – Gocht Jun 25 '15 at 21:41
  • Remember you are inside a `try - except` block, so if an error is happening that will just `pass`. – Gocht Jun 25 '15 at 21:49