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:
- The message appears in the verify view -- currently I remove all messages from that view, but this isn't ideal.
- 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?