Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How can I check the last activity time of user if user didn't log out?

django's User model has a last_login field, which is great if all the users were to log out each time they leave the site, but what if they don't?

How can I track when a user who never logged out and his activity on the site?

like image 253
la_f0ka Avatar asked Feb 04 '13 11:02

la_f0ka


People also ask

How does django track user activity?

Go to the Django Admin by changing the URL in your browser to "http://localhost:8000/admin". The Django Admin login page will appear. Enter the username and password of the superuser you just created with the manage.py command to log in. Next, you will see the Django admin dashboard.

How long does django session last?

As you mentioned in your question, sessions in Django live for as long as SESSION_COOKIE_AGE determines (which defaults to 2 weeks) from the last time it was "accessed". Two exceptions for that: you can set an expiry time to a session yourself, and then it depends on that.

How can I see user details in django?

Each profile uses the users username to create a url for their profile. Currently if I sign in as one user and change the URL to another users profile URL, it still displays the current users profile. I want something similar to pinterest where any person whether they are signed in or not can view peoples profiles.

How do you check if a user is online in django?

But the correct way to check if a user is logged in or not is to use : request. user. is_authenticated. This will return True if the person is logged in other wise False.


3 Answers

You need to have the last_activity field in the user profile (or custom user model). This field will be updated on every request. To achieve this you need to have custom middleware:

profiles/middleware.py:

from django.utils import timezone

from myproject.profiles.models import Profile


class UpdateLastActivityMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        assert hasattr(request, 'user'), 'The UpdateLastActivityMiddleware requires authentication middleware to be installed.'
        if request.user.is_authenticated():
            Profile.objects.filter(user__id=request.user.id) \
                           .update(last_activity=timezone.now())

Add this middleware in your setting file:

MIDDLEWARE_CLASSES = (
    # other middlewares
    'myproject.profiles.middleware.UpdateLastActivityMiddleware',
)
like image 85
Aamir Rind Avatar answered Oct 19 '22 02:10

Aamir Rind


I know the question is old ... and surely it has already been solved ... but here is my contribution ... In new versions of django you can use:

"Session Time" -> Used in configuration file. "settings.py"

If the user closes the browser, the session ends and must be logged in again ...
SESSION_EXPIRE_AT_BROWSER_CLOSE = True

If the user does not close the browser, you can set a time limit for the session ...
SESSION_COOKIE_AGE = 60 * 60 

For "SESSION_COOKIE_AGE" if I remember correctly it's defined in seconds. You can see more here... Recommended reading is also django's own documentation about sessions...

like image 3
Torrez Milton N. Avatar answered Oct 19 '22 02:10

Torrez Milton N.


i think in 2022 this will satisfy what you need also i did this and worked for me but the answer didnt.

put LastActivityTraceMiddleware after AuthenticationMiddleware in settings.py.

from django.utils.timezone import now
from .... import MemberEntity


class LastActivityTraceMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        member: MemberEntity = request.user
        if member.is_authenticated:
            member.last_login = now()
            member.save()
        return response
like image 2
Samurai jk Avatar answered Oct 19 '22 02:10

Samurai jk