Search code examples
djangodjango-viewsdjango-middlewaredjango-messages

Django show message in every view


I want to show a message in every view in my Django project. Once a user has created an account, I send them an email asking them to verify their email and until they have verified their email address (by visiting a verify URL) I'll show the message.

Now, I don't want to show the message on the verify URL view and I don't want the message to be "duplicated" i.e. show two of the same messages. Initially I tried the approach of creating a middleware that will simply add the message to every response but this has 2 downsides:

  1. The message appears in the verify view -- currently I remove all messages from that view, but this isn't ideal.
  2. When I use a redirect in my view, I get more than one of the same message. Most of the redirects I use are after a POST so I could check if the request is a GET but that doesn't feel right.

Here's the middleware:

class VerifiedEmailMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        if request.user.id is None:
            return self.get_response(request)

        if not request.user.profile.verified_email:
            messages.warning(request, 'We have sent you an email to verify your account. '
                                      'Please click the link in that email to verify your account.')

        response = self.get_response(request)

        return response

Is there a standard, or better, way to do this?


Solution

  • You can achieve this by simply creating context processor and can check user is verified or not. According to it you can pass some context to your template. Like:

    def myContextProcessor(request):
        return {
           "is_loggedIn": True
        }
    

    and register it in settings.py

    'context_processors': [
        ...,  
        'project.context_processors.myContextProcessor'
    ]