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:
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?
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'
]