Evgenii Legotckoi
Evgenii LegotckoiOct. 25, 2018, 2:47 a.m.

Django - Tutorial 039. Adding private messages and chats on the site - Part 2 (Dialogue and chat counter with unread messages)

Gave free time to correct private messages on the site. This functionality is not used very often, so I do not make great efforts to improve it, although it is time to bring this functionality to adequate work.

Previously, there was a very big flaw, which was that the dialogue counter with unread messages was not shown, which led to the fact that the users who were sent the message simply did not pay attention to it, because they did not know about it.

Now I finally fixed this flaw. And in the framework of the previous code I will show which corrections were added.

I thought about two options for organizing unread messages counters. Rather, one of the options and its more advanced version.

  • For each request, check all chats, select the latest messages from them and check whether the author is the authorized user for whom you want to check this message. If he is not the author, then we check if the message has been read, if not, then we consider this dialogue unread for this user. The number of such dialogs will be considered the number of unread dialogs.
  • А второй вариант, на котором я остановился предполагает ту же самую логику, только диалог или чат должен иметь внешний ключ на самое последнее сообщение, которое было в него добавлено. Данный ключ будет обновляться при каждом новом сообщении. Тогда отпадает необходимость выборки сообщений по чату и их сортировки, чтобы получить самое последнее сообщение. Что, по-моему мнению может вылиться в большие накладные расходы для базы данных, если диалогов будет очень много.



Add a foreign key to the last message, as well as the ChatManager chat manager.

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

#... Code from the previous part

class ChatManager(models.Manager):
    use_for_related_fields = True

    # The method accepts the user for which the sample should be made.
    # If the user is not added, all dialogs will be returned,
    # in which at least one message is not read
    def unreaded(self, user=None):
        qs = self.get_queryset().exclude(last_message__isnull=True).filter(last_message__is_readed=False)
        return qs.exclude(last_message__author=user) if user else qs

class Chat(models.Model):
    #... Code from the previous part

    # foreign key to the last message,
    # The important point is that the name of the Message class is written in the usual string,
    # because at the time of reading the Chat class the Python interpreter knows nothing about the Message class
    # You also need to add related_name, the name through which the selection of this message from the database will be associated
    last_message = models.ForeignKey('Message', related_name='last_message', null=True, blank=True, on_delete=models.SET_NULL)

    objects = ChatManager()

    def get_absolute_url(self):
        return 'users:messages', (), {'chat_id': self.pk }

class Message(models.Model):
    #... Code from the previous part


This is the first time I've been writing such a Python file in a project on Django. Its essence is that signal handlers from the model will be declared there. The fact is that in Django, while saving the model object, some signals are emitted that can be processed. This allows you to put some uniform logic in a separate file and make the rest of the project code a bit cleaner. The downside is that this code may not be obvious, since there will be no references to this code in other parts of the project.

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

from django.db.models.signals import post_save
from django.dispatch import receiver

from users.models import Message

# message object save handler
@receiver(post_save, sender=Message)
def post_save_comment(sender, instance, created, **kwargs):
    # if the object was created
    if created:
        # we indicate to the chat room where this message is located, that this is the last message
        instance.chat.last_message = instance
        # and update this foreign chat key

But just this code will not work, because this file also needs to be loaded into the interpreter.

This can be done in the apps.py file when the application is initialized.


This is done in the ready method

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

from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _

class UsersConfig(AppConfig):
    name = 'users'
    verbose_name = _('Users')

    def ready(self):
        import users.receivers


Now that you have everything you need to get the number of conversations with unread messages, you can add this information to the context for rendering the template.

context['unreaded_dialogs_counter'] = user.chat_set.unreaded(user=user).count()

How to fix the old dialogues

It remains only to correct the old dialogues that already have messages. This can be done through the admin panel, if you add the appropriate action.


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

from django.contrib import admin

from users import models

class ChatAdmin(admin.ModelAdmin):
    autocomplete_fields = ['members']
    search_fields = ('members',)
    actions = ['fix_last_messages']

    def fix_last_messages(self, request, queryset):
        for chat in queryset.all():
            chat.last_message = chat.message_set.all().order_by('-pub_date').first()

    fix_last_messages.short_description = "Fix last messages"

class MessageAdmin(admin.ModelAdmin):
    autocomplete_fields = ['chat', 'author']
    list_display = ('chat', 'author', 'message', 'pub_date', 'is_readed')

admin.site.register(models.Chat, ChatAdmin)
admin.site.register(models.Message, MessageAdmin)
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.

Do you like it? Share on social networks!

  • Aug. 4, 2020, 2:19 a.m.
  • (edited)

Здравствуйте, подскажите как именно должна выглядеть уже готовая вьюха с context? Не догоняю как его вставить

  • Aug. 4, 2020, 2:25 a.m.

Может быть посоветуете как добавить необязательное поле + прокинуть его во вьюху что бы можно было отправлять небольшие документы.?

  • Aug. 5, 2020, 4:20 a.m.

Этот вопрос я решил)

Evgenii Legotckoi
  • Aug. 5, 2020, 5:14 a.m.

Добавляйте поле файла в модель сообщения. И в форме сообщения указывайте, что поле с файлом.


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

Qt - Test 001. Signals and slots

  • Result:57points,
  • Rating points-2

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

  • Result:60points,
  • Rating points-1

C++ - Test 005. Structures and Classes

  • Result:0points,
  • Rating points-10
Last comments
JonnyJoJune 8, 2023, 12:14 p.m.
Qt/C++ - Lesson 019. How to paint triangle in Qt5. Positioning shapes in QGraphicsScene Евгений, здравствуйте! Решил поэкспериментировать немного с кодом из этого урока, нарисовать вместо треугольника квадрат и разобраться с координатами. В итоге, запутался. И ни документация,…
JonnyJoMay 25, 2023, 2:24 p.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю!
Evgenii Legotckoi
Evgenii LegotckoiMay 25, 2023, 4:49 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Код на строчка 184-198 вызывает перерисовку области на каждый 4-й такт счётчика. По той логике не нужно перерисовывать объект постоянно, достаточно реже, чем выполняется игровой слот. А слот вып…
JonnyJoMay 21, 2023, 10:49 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю! Всё равно не совсем понимаю :( Если муха двигает ножками только при нажатии клавиш перемещение, то что, собственно, делает код со строк 184-198 в triangle.cpp? В этих строчка…
Evgenii Legotckoi
Evgenii LegotckoiMay 21, 2023, 5:57 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Добрый день. slotGameTimer срабатывает по таймеру и при каждой сработке countForSteps увеличивается на 1, это не зависит от нажатия клавиш, нажатая клавиша лишь определяет положение ножек, котор…
Now discuss on the forum
TwangerJune 7, 2023, 11:12 a.m.
Ошибка при выполнении триггерной функции (GreenPlum) Есть 3 таблицы fact_amount со структурой: CREATE TABLE fact_amount ( id serial4 NOT NULL, fdate date NULL, type_activity_id int4 NULL, status_id int4 NULL, CONSTRAINT fact…
Alexander RyabikovJune 6, 2023, 1:35 p.m.
Работа с QFileSystemModel Вопросик по теме QFileSystemModel в Linux. Он, как и положено, обновляется самостоятельно, если директория локальная. Но, вот, сетевая папка (у меня шара samba) не обновляется. Как её можно…
Evgenii Legotckoi
Evgenii LegotckoiApril 16, 2023, 4:07 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Да, это возможно. Но подобные вещи лучше запускать через celery. То есть drf принимает команду, и после этого регистрирует задачу в celery, котроый уже асинхронно всё это выполняет. В противном …
Алексей БобровDec. 14, 2021, 7:03 p.m.
Sorting the added QML elements in the ListModel I am writing an alarm clock in QML, I am required to sort the alarms in ascending order (depending on the date or time (if there are several alarms on the same day). I've done the sorting …

Follow us in social networks