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

django, сообщение, Python, чат

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': }

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
        # and update this foreign chat key['last_message'])

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

This can be done in the 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'), ChatAdmin), 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.
Support the author Donate


Only authorized users can post comments.
Please, Log in or Sign up
How to become an author?

Contribute to the evolution of the EVILEG community.

Learn how to become a site author.

Learn it

Good day, Dear Users!!!

I am Evgenii Legotckoi, developer of EVILEG. And it is my hobby project, which helps to learn programming another programmers and developers

If the site helped you, and you want also support the development of the site, than you can donate by following ways


Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting Timeweb
May 25, 2020, 11:33 a.m.
Mitja Nagibin

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

  • Result:50points,
  • Rating points-4
May 25, 2020, 5:05 a.m.

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

  • Result:66points,
  • Rating points-1
May 25, 2020, 3:30 a.m.
just maks

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

  • Result:80points,
  • Rating points4
Last comments
May 26, 2020, 6:51 a.m.
Evgenij Legotskoj

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

У вас база данных не открылась Исправьте путь к базе данных на свой корректный в следующих методах void DataBase::connectToDataBase() bool DataBase::openDataBase()
May 26, 2020, 6:22 a.m.
Tima 1

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

полностью повторил структору проекта. В форму дабавил tableView. Но при запуске получаю форму только с пустым tableView. Можете подсказать в чем пробелма?
May 26, 2020, 6:02 a.m.
Evgenij Legotskoj

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

Потому что это файл который нужно создать, а не библиотека. В статье есть содержание этого файла. Добавляйте в проект. Копируйте содержимое из статьи.
May 26, 2020, 6 a.m.
Tima 1

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

не удается подключиить библеотеку include "database.h" выдает ошибку. Можете помочь?
Now discuss on the forum
May 26, 2020, 5:16 a.m.

Отсутствие драйвера SQLite в пакете Qt 4 на Linux

Вот честно непонимаю почему до сих пор используют qt4, там же столько всего отсутствует, много фишек и возможностей нету там. То есть используя такое старье приходится много писать самому а не и…
May 26, 2020, 2:24 a.m.
Dzhon Kofi

Disable autoscroll

такие естественные решения все перепробовал. Получилось вчера так: const int maximumScroll = ui->_samples->verticalScrollBar()->maximum();const int sliderPos = ui->_samp…
May 26, 2020, 12:43 a.m.
Ruslan Polupan

Посоветуйте новичку (базы данных и Qt, что учить)

Без БД сейчас практически никуда. Поэтому SQL надо знать. SQLite самы простой вариант, но имхо лучще начать с бд клиент-сервер. Настроить сервер. Подключаться клиентом. Просто это помогает понят…
May 25, 2020, 2:42 p.m.
Esteban José María

Компиляция пустого проекта Qt Android

qt 5.12.8 BUILD SUCCESSFUL in 42s 28 actionable tasks: 28 executed Android package built successfully in 68.251 ms. Ну, буду разбираться по-тихоньку. :)
May 25, 2020, 1:24 p.m.

Использование файлов в памяти (memory file mapping)

Добрый вечер, проблемы работы с файлом Exel нет вообще. Весь смысл в том чтобы не создавать на диске физический файл (требования безопасности), дабы потом не чистить. А так вопрос только в этом …
© EVILEG 2015-2020
Recommend hosting TIMEWEB