Evgenii Legotckoi
Oct. 25, 2018, 12:47 p.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.
  • А второй вариант, на котором я остановился предполагает ту же самую логику, только диалог или чат должен иметь внешний ключ на самое последнее сообщение, которое было в него добавлено. Данный ключ будет обновляться при каждом новом сообщении. Тогда отпадает необходимость выборки сообщений по чату и их сортировки, чтобы получить самое последнее сообщение. Что, по-моему мнению может вылиться в большие накладные расходы для базы данных, если диалогов будет очень много.

Implementation

models.py

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

  1. # -*- coding: utf-8 -*-
  2.  
  3. #... Code from the previous part
  4.  
  5.  
  6. class ChatManager(models.Manager):
  7. use_for_related_fields = True
  8.  
  9. # The method accepts the user for which the sample should be made.
  10. # If the user is not added, all dialogs will be returned,
  11. # in which at least one message is not read
  12. def unreaded(self, user=None):
  13. qs = self.get_queryset().exclude(last_message__isnull=True).filter(last_message__is_readed=False)
  14. return qs.exclude(last_message__author=user) if user else qs
  15.  
  16.  
  17. class Chat(models.Model):
  18. #... Code from the previous part
  19.  
  20. # foreign key to the last message,
  21. # The important point is that the name of the Message class is written in the usual string,
  22. # because at the time of reading the Chat class the Python interpreter knows nothing about the Message class
  23. # You also need to add related_name, the name through which the selection of this message from the database will be associated
  24. last_message = models.ForeignKey('Message', related_name='last_message', null=True, blank=True, on_delete=models.SET_NULL)
  25.  
  26. objects = ChatManager()
  27.  
  28. @models.permalink
  29. def get_absolute_url(self):
  30. return 'users:messages', (), {'chat_id': self.pk }
  31.  
  32.  
  33. class Message(models.Model):
  34. #... Code from the previous part

receivers.py

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.

  1. # -*- coding: utf-8 -*-
  2.  
  3. from django.db.models.signals import post_save
  4. from django.dispatch import receiver
  5.  
  6. from users.models import Message
  7.  
  8.  
  9. # message object save handler
  10. @receiver(post_save, sender=Message)
  11. def post_save_comment(sender, instance, created, **kwargs):
  12. # if the object was created
  13. if created:
  14. # we indicate to the chat room where this message is located, that this is the last message
  15. instance.chat.last_message = instance
  16. # and update this foreign chat key
  17. instance.chat.save(update_fields=['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 apps.py file when the application is initialized.

apps.py

This is done in the ready method

  1. # -*- coding: utf-8 -*-
  2.  
  3. from django.apps import AppConfig
  4. from django.utils.translation import ugettext_lazy as _
  5.  
  6.  
  7. class UsersConfig(AppConfig):
  8. name = 'users'
  9. verbose_name = _('Users')
  10.  
  11. def ready(self):
  12. import users.receivers

Using

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.

  1. 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.

admin.py

  1. # -*- coding: utf-8 -*-
  2.  
  3. from django.contrib import admin
  4.  
  5. from users import models
  6.  
  7.  
  8. class ChatAdmin(admin.ModelAdmin):
  9. autocomplete_fields = ['members']
  10. search_fields = ('members',)
  11. actions = ['fix_last_messages']
  12.  
  13. def fix_last_messages(self, request, queryset):
  14. for chat in queryset.all():
  15. chat.last_message = chat.message_set.all().order_by('-pub_date').first()
  16. chat.save(update_fields=['last_message'])
  17.  
  18. fix_last_messages.short_description = "Fix last messages"
  19.  
  20.  
  21. class MessageAdmin(admin.ModelAdmin):
  22. autocomplete_fields = ['chat', 'author']
  23. list_display = ('chat', 'author', 'message', 'pub_date', 'is_readed')
  24.  
  25.  
  26. admin.site.register(models.Chat, ChatAdmin)
  27. admin.site.register(models.Message, MessageAdmin)

Recommended articles on this topic

By article asked1question(s)

2
Anton
  • Aug. 4, 2020, 12:19 p.m.
  • (edited)

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

Anton
  • Aug. 4, 2020, 12:25 p.m.

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

Anton
  • Aug. 5, 2020, 2:20 p.m.

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

Evgenii Legotckoi
  • Aug. 5, 2020, 3:14 p.m.

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html