Django - Tutorial 048. How to add online status to a site

Auth, Django, Backend, Python

For a long time I did not add such functionality on the site for the simple reason that I did not know which side to approach this, because I would like to process this information in one single place, and not in every View.

Over time, I began to modify Backend classes for the site and the solution came by itself. It was only necessary to modify each authentication backend that is used on the site. And rewrite the get_user method, which will store information about the user's last request to the site. And the online status can be saved for the last 15 minutes, then the status will be offline.

And the date of the last request can be stored either in the user’s profile, which will be the OneToOne model for the user, or override the user model. I chose the option of overriding the user model.


Let's create our own authentication module my_auth, if you have not created it yet

python startapp my_auth

Then redefine the user model

# -*- coding: utf-8 -*-

from django.contrib.auth.models import AbstractUser
from django.contrib.humanize.templatetags.humanize import naturaltime
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

class User(AbstractUser):

    last_online = models.DateTimeField(blank=True, null=True)

    # In this method, check that the date of the last visit is not older than 15 minutes
    def is_online(self):
        if self.last_online:
            return ( - self.last_online) < timezone.timedelta(minutes=15)
        return False

    # If the user visited the site no more than 15 minutes ago,
    def get_online_info(self):
        if self.is_online():
            # then we return information that he is online
            return _('Online')
        if self.last_online:
            # otherwise we write a message about the last visit
            return _('Last visit {}').format(naturaltime(self.last_online))
            # If you have only recently added information about a user visiting the site
            # then for some users there may not be any information about the visit, we will return information that the last visit is unknown
        return _('Unknown')

Next, we write our own authentication backend, which will replace the Django backend.

# -*- coding: utf-8 -*-

from django.contrib.auth import get_user_model
from django.utils import timezone

class MyBackend:

    def get_user(self, user_id):
            user = get_user_model().objects.get(pk=user_id)
            user.last_online =  # At the request of the user, we will update the date and time of the last visit
            return user
        except get_user_model().DoesNotExist:
            return None

Do not forget to register our application ...


... and add authentication backend



Now, at each user request to the site, your user will be updated with information about his last visit.

And you can do in the template with users in the content whether it is online or not. For example, to add an Online icon to an avatar

{% if user.is_online %}
    <div class="online"></div>
{% endif %}

or so display information about his online status.

<span class="text-muted">{{ user_profile.get_online_info }}</span>

A possible disadvantage of this method is that the user can open the page and do nothing for an entire hour on it.
But in my case, this is not a problem, because I call the status information of an authenticated user every minute, so that while the user’s page remains open, his online status is updated every minute.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
- company blog
Support the author Donate


Only authorized users can post comments.
Please, Log in or Sign up
Looking for a Job?
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

Sept. 17, 2019, 8:51 a.m.
Julija Aleksandrova

C++ - Test 001. The first program and data types

  • Result:33points,
  • Rating points-10
Sept. 17, 2019, 8:36 a.m.
Julija Aleksandrova

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:10points,
  • Rating points-10
Sept. 16, 2019, 11:47 a.m.
Viktor Dzen'kiv

C++ - Test 002. Constants

  • Result:75points,
  • Rating points2
Last comments
Sept. 17, 2019, 6:07 a.m.
Misha Lebedev

Кстати интересные темы нашёл тут Может что полезного тоже Евгений найдёте
Sept. 17, 2019, 4:50 a.m.
Misha Lebedev

Доброго времени суток. Спасибо за хороший ответ, У меня ситуация така что в галлереи будет несколько миллионов фотографий с фильтрами и тегами , и я опасаюсь за производительност . Это ос…
Sept. 17, 2019, 3:23 a.m.
Evgenij Legotskoj

Добрый день. Да, я тоже читал ту статью в своё время и согласен с тем, что внешние ключи гораздо лучше, чем GenericForeignKey. Выборки в ряде случае работают быстрее. Но лично мне про…
Sept. 14, 2019, 5:08 p.m.
Misha Lebedev

Приветствую вас Евгений , давно наблюда за развитием вашего замечательного портала, много полезно тут нашел , переодически зачитываюсь. Теперь по сушеству, делаю портал и там идеально ложи…
Sept. 10, 2019, 4:38 p.m.
Evgenij Legotskoj

function view для модели Article и LikeDislike.LIKE будет выглядеть так def like(request, pk): obj = Article.objects.get(pk=pk) try: likedislike = LikeDislike.objects.get(cont…
Now discuss on the forum
Sept. 17, 2019, 5:02 a.m.

Да, действительно нужно дебажить, по другому не словить исключение. Уже решил проблему, был выход за предел массива, не правильные входные данные, так что всегда проверяйте размер массива.
Sept. 17, 2019, 3:39 a.m.
Evgenij Legotskoj

Добрый день! На удалённом сервере вряд ли. Этот класс из core модуля, а удалённый сервер - это ещё и network модуль нужно подтягивать. Тут на удалэнном сервере нужно делать программу…
Sept. 17, 2019, 3:30 a.m.
Evgenij Legotskoj

Добрый день! Попробуйте toHex() А также создние QString с помощью from методов. Может быть QString::fromLatin1(). В документации на QString почти два десятка методов from, один из них…
Sept. 16, 2019, 1:54 p.m.

Однозначно PostgreSql не ниже 10 ки.
Sept. 16, 2019, 7:09 a.m.

прочитайте QMAKE_POST_LINK += "~/Qt/5.12.0/clang_64/bin/macdeployqt $${TARGET}.app $$escape_expand( \\n\\t )"
© EVILEG 2015-2019
Recommend hosting TIMEWEB