NodeReact020
NodeReact020

Reputation: 506

Django - Checking if user has logged in before

when a user signs up, they get redirected to the homepage. If it is their first time logging in, I want to display a div, however if it is not their first time, I do not want this div to appear. Currently, I am relying on date_joined andlast_login to do this check.

However this only checks dates and not the time. Therefore the div will still appear until the date has changed. I only want the div displayed once. This is when the user first logs in.

Here is my code so far: views.py:

def home(request):
    context={}
    user = request.user
    if user.last_login.date() == user.date_joined.date():
        context['isFirstTime'] = 'isFirstTime'
    else:
        pass
    return render(request, 'home.html', context)

template:

   {% if isFirstTime %}
        <div style="width: 300px; height: 300px; background-color: green;">

        </div>
    {% endif %}

Does anybody know how I can alter this so it works with the current time and not the current date. This way the div is only displayed when a user first logs in. Anybody know a solution? Thank you. Also date_joined and last_login are datetime objects stored in the database.

Upvotes: 0

Views: 309

Answers (2)

Yellowduck
Yellowduck

Reputation: 492

Instead of using last_login and date_joined, consider creating a UserProfile model with an attribute is_first_login, you can read more about UserProfile here .

In your models.py:

class UserProfile(models.Model):  
    user = models.OneToOneField(User, related_name='profile')
    is_first_login = models.BooleanField(default=True)  

In your view:

def home(request):
    context={}
    user = request.user
    if user.profile.is_first_login:
        context['isFirstTime'] = 'isFirstTime'
        user.profile.is_first_login = False
        user.profile.is_first_login.save()
    else:
        pass
    return render(request, 'home.html', context)

Upvotes: 2

Andrey Nelubin
Andrey Nelubin

Reputation: 3294

if (user.last_login - user.date_joined).total_seconds() < 5:
    ... # do your code
    user.last_login = datetime.datetime.now()
    user.save()

Both last_login and date_joined are DateTime instances so you need to compare them directly. But I recommend you to add some delta, like 5 seconds in example before to be sure

Upvotes: 1

Related Questions