[Django]-Django – Show message in template if this user has not been on the site before

3👍

Assuming you only want to show that banner at the top of the page for logged in users (those that have a User instance in the current request), you could create a Model (or, if you have your own user profile model, add a field to it) to save that.

class Access(models.Model):
    user = models.ForeignKey(User)
    has_been_here_before = models.BooleanField(default=False)

In your view you would have to check that Model to see if the user is registered there and has the flag set.

See this post for detecting first login.

See also this similar post for detecting a visit to each individual page or view.


EDIT: according to your comments you want to show the welcome banner to anonymous users (not logged in) if they visit for the first time.

You could achieve that using djangos session framework. You can use request.session just like a simple dict.

In your home page view (or through a custom middleware so it affects all pages not just the home page) you could check if a user has already dismissed the welcome banner or not.

def my_home_view(request):
    ...
    # as default 'show_welcome_banner' will be True
    context['show_welcome_banner'] = request.session.get('show_welcome_banner', True)
    ...

Then, in your template use:

{% if show_welcome_banner %}
    <h3>First time here?</h3>
    <h5>Follow these steps...</h5>
{% endif %}

Your banner could have a ‘dismiss’ button that posts a hidden to a different url (maybe even through ajax). This url would alter the users session info:

def dismiss_welcome_banner(request):
    ...
    if request.method == 'POST':
        request.session['show_welcome_banner'] = False
    ...

Notes:

  1. if a user access the site through incognito mode (the session c**kie gets deleted when he closes the browser) he will need to click the dismiss button every time he opens the incognito browser.
  2. You could additionally check that loggen in users do not get to see that banner, depending of how you prefer it.
👤Ralf

Leave a comment