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.

my_auth

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

python manage.py startapp my_auth

models.py

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 (timezone.now() - 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')

backends.py

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):
        try:
            user = get_user_model().objects.get(pk=user_id)
            user.last_online = timezone.now()  # At the request of the user, we will update the date and time of the last visit
            user.save(update_fields=['last_online'])
            return user
        except get_user_model().DoesNotExist:
            return None

settings.py

Do not forget to register our application ...

INSTALLED_APPS = [
    'my_auth.apps.MyAuthConfig',
    ...
]

... and add authentication backend

AUTHENTICATION_BACKENDS = (
    'my_auth.backends.MyBackend',
    'django.contrib.auth.backends.ModelBackend',
)

Conclusion

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Donate

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

n
Nov. 16, 2019, 1:28 a.m.
nick

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

  • Result:80points,
  • Rating points4
D
Nov. 15, 2019, 10:16 a.m.
Daulet

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

  • Result:40points,
  • Rating points-8
LP
Nov. 12, 2019, 7:22 p.m.
Lev Parhimovich

C++ - Test 006. Enumerations

  • Result:50points,
  • Rating points-4
Last comments
b
Nov. 9, 2019, 7:28 p.m.
bastonc

спасибо ещё раз. огромное, за уделённое время
b
Nov. 9, 2019, 7:24 p.m.
bastonc

Спасибо Вам большое. Буду изучать.
Nov. 9, 2019, 4:58 p.m.
Evgenij Legotskoj

Добрый день. По первым двум вопросам вы найдёте ответ в этой статье - PyQt5 - Урок 008. Работа с QTableWidget (Обновление урока 006) Что касается последнего вопроса, то я вам…
Nov. 9, 2019, 1:50 p.m.
Evgenij Legotskoj

Как и обещал, вы можете посмотреть новую статью QML - Урок 037. Кастомизация кнопок в QML (Обновление урока 002) . Там же найдёте ссылку на Git репозиторий. Не забудьте поставить звёз…
b
Nov. 8, 2019, 6:40 p.m.
bastonc

Приветствую. Подскажите пожалуйста пару моментов. 1. Как сделать столбец не редактируемый, а остальные ячейки остаются редактируемыми 2. Как оталвливать события двойного клика для реда…
Now discuss on the forum
s
Nov. 15, 2019, 10:06 p.m.
sladkoewka

За пример буду очень благодарен, т.к. я новичок и с подобным пока не работал.
Nov. 15, 2019, 6:37 p.m.
Intruder

Евгений, почитав про эту проблему пришел к выводу, что либо нужно говорить очередь, либо все вернуть из библиотеки (dll в моем случае) в приложение, потому что в приложении все работает просто з…
Nov. 15, 2019, 5:06 p.m.
Evgenij Legotskoj

Ну тогда не знаю )) Я большую часть времени на C++ с Qt работаю, а PyQt5 у меня боком. Так что, чем можем помочь ))
H
Nov. 15, 2019, 4:18 p.m.
Hyperfish

Да, пробовал, с преобразованием int array[]={1,2,3,4,5,6,7} в jintArray(array). Если так, то программа компилируется без ошибок и предупреждений, но вываливается с ошибкой времени выполнени…
Nov. 15, 2019, 2:48 p.m.
Evgenij Legotskoj

Ну собственно поэтому я и сказал, что бесполезное это занятие.
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB