Add a message on all views in Django

Viewed 127

I'd like to use the Django messages framework to show a message to users visiting our website. The idea is to show it on the first page they view and then not show it again for the rest of the user session.

I'm thinking it will work a bit like this:

if request.session.get('show_welcome_message', True):
    messages.info(request, 'Welcome to our site!')
    request.session['show_welcome_message'] = False

My question is, where's the best place to add this to have it show on all website pages?

And, is there a better way to do something like this that makes use of Django's native messaging to display a message to users that they don't see again on the same session if they close the message?

1 Answers

You can create a middleware for this.


The idea is to show it on the first page they view and then not show it again for the rest of the user session.

If your idea of a session is everytime a new browser/tab is opened. This line may not help: request.session['show_welcome_message'] = False

This is because django's session persists event after closing the browser.

I would suggest to use the browser's SessionStorage on the client side alongside and some ajax to reliably check whether it's a first time visit.

Related