How to Track User Logins in Django



Python


In this article, we show how to track user logins in Django.

So any website that has users contains a login form, so that users can log into their account on the site.

Many websites track the times when a user logs in. This is why on many sites, you are able to see the 'Last Log in' for a user.

Now if you want to implement a similar system on your Django website, how can this be done?

And the solution is relatively easy.

So you can create a model that stores the user and the login time when a user logins in.

And whenever we log a user in, we can create an instance of this model, which shows the user and the login time.

To show the last log in time, for instance, we would order the results according to the log in time and get the last result.

So this is the approach we take for this.

models.py File

We create a model that simply has 2 columns, user and date.

This is shown in the code below.



So we have created a model, called AllLogin, which has 2 rows, user and date.

This model will contain two pieces of data. Every time a user logs in, we save that user and the time logged in. This way, we save each user that logs in and the time. This way, we can know all the times that a user has logged in. We also can obviously know the last time a user has logged in.

This will tell us which user logged in and at what time.

This is all the code we need in the models.py file.

After this, you just have to run, py manage.py makemigrations and py manage.py migrate, in order for the changes to be made into effect.

views.py File

Now that the model is created, we now have to write our code within the views.py file.

So basically every time a user logs in, we want to create an instance of the AllLogin model, which tracks which user logged in and at what time.

This is done in the following code below.



So once a user is logged in with your code, then all you have to do is create an instance of the AllLogin model, with the user being set to request.user

This creates a record of the current login.

Every time a user logs in, the user and the time logged in is saved in the database.

Thus, now we have record of user logins.

And this is how we can track user logins in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...