Saving "last seen" time doesn't work beyond a few seconds

Based on this question I added the following middleware to track users' last seen date:

from datetime import datetime, timedelta
from dateutil.parser import parse

from .models import User

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

    def __call__(self, request):
        if request.user.is_authenticated:
            last_seen = request.session.get("last-seen")
            now = datetime.now()
            too_old_time = now - timedelta(seconds=60*60)

            if not last_seen or parse(last_seen) < too_old_time:
                User.objects.filter(id=request.user.id).update(last_seen=now)

            request.session["last-seen"] = now.isoformat()

        return self.get_response(request)

This works when I set the timedelta to only a few seconds, but anything more and it stops updating the field. Am I missing something obvious?

Вернуться на верх