[Answer]-Django call custom middleware only when user is logged in

1👍

Middleware is run every time a request or response is processed. You can’t conditionally execute it. That is, if your middleware class has methods like process_request, process_response etc. they will always be called.

Try something like this:

class get_username(object):

   def process_request(self, request):
       if request.user.is_authenticated():
           # ...
           request.session['display_name'] = display_name
           request.session.save()
👤Matt

Leave a comment