Evgenii Legotckoi
Evgenii LegotckoiMay 10, 2017, 12:38 p.m.

Django - Tutorial 024. Polling with AJAX

Frequent surveys with AJAX allow you to establish a permanent connection between the browser and the server in order to update any data, for example, whether there are new notifications on the site for the user. For example, I organized a small system of notifications for registered users, which allows them to find out at the entrance to the site if there were answers in the articles and forum questions to which they are subscribed, and whether there were new articles and questions on the forum, to sections of which users were also signed.

The notifications are as follows:


Principle of polling operation

The principle is that requests are sent from the user's browser with a certain periodicity, and they check whether there are any changes on the server or not. In case there are any changes, the server sends a response with these changes, otherwise sends a negative result.

To organize the polling frequency, you can use the function setInterval() , which specifies the function and period of the call of this function.

setInterval(function () {
    $.ajax({
        url: "/get_notifications/",
        type: 'POST',
        data: {'check': true},

        success: function (json) {
            if (json.result) {
                $('#notify_icon').addClass("notification");
                var doc = $.parseHTML(json.notifications_list);
                $('#notifications-list').html(doc);
            }
        }
    });
}, 60000);

In this case, the notification is checked once a minute, and if the result of the check is positive, then notifications in the notification panel are replaced by those that were sent from the server. And also the bell of notifications is highlighted in red.

Since the site is running on the VDS server and at the moment does not have such a load, which would be tangible for the server, I render notifications immediately on the server and send the ready-made html code that I want to add to the page in the required place. With increasing load, of course, we will consider the option of sending the purely information that is required to be inserted into the site, and the template will be already javascript code. But this will be realized later

As for the above code, then:

// Highlight the bell
$('#notify_icon').addClass("notification");
// Create HTML code from the JSON variable
var doc = $.parseHTML(json.notifications_list);
// We replace the html code inside the notification bar
$('#notifications-list').html(doc);

On the Django side, you need to write a view that will be responsible for verifying that the user has notifications:

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

import json

from django.http import HttpResponse
from django.views import View
from django.template.loader import render_to_string

class CheckNoticeView(View):
    def post(self, request):

        result = request.user.notice_set.has_unreaded()

        if result:
            return HttpResponse(
                json.dumps({
                    "result": result,
                    "notifications_list": render_to_string('notifications_list.html', {'user': request.user}),
                }),
                content_type="application/json"
            )
        else:
            return HttpResponse(
                json.dumps({
                    "result": result,
                }),
                content_type="application/json"
            )

In this case, requests are performed only for authorized users, which is controlled by the decorator login_required() in the urls.py file. Therefore, we take the user out of the request and check for unread notifications.

request.user.notice_set.has_unreaded()
  • notice_set - This is query_set of notifications that relate to the user
  • has_unreaded() - This is a special method in the Custom ModelManager that returns true if there are unread notifications and false otherwise.

Further, if there are notifications, then the last 5 pieces are rendered into the HTML code sorted by date and status (Read / Not Read).

In the simplest template, this might look like this:

{% for notice in user.notice_set.all|dictsortreversed:"date"|dictsort:"is_readed"|slice:":5" %}
    <div>
        {{ notice.content }}
    </div>
{% endfor %}

In the urls.py file, the view connection looks like this:

url(r'^notice/(?P<pk>\d+)/read/$',
    login_required(views.ReadNoticeView.as_view()),
    name='notice_read'),

Conclusions

In this way, you can organize server polls that will take new notifications from the site for authorized users. This is the most simple mechanism for periodically updating information on the page without rebooting, but also the most expensive on resources.

If your site is on a VDS server and at the same time the load is currently low, and the functionality is very desirable to implement, then this will be the simplest and most effective way to implement some realtime on the site, but you need to monitor the load and, with a significant increase in attendance, move to more efficient ones Techniques for updating information, such as Long Polling and Web Sockets.

For Django I recommend VDS-server of Timeweb hoster .

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!

d
  • Feb. 26, 2018, 7:50 a.m.

спасибо, продолжай в том же духе

Comments

Only authorized users can post comments.
Please, Log in or Sign up
1
  • 12333
  • July 18, 2024, 3:34 p.m.

Qt - Test 001. Signals and slots

  • Result:63points,
  • Rating points-1
1
  • 12333
  • July 18, 2024, 3:25 p.m.

C++ - Test 005. Structures and Classes

  • Result:50points,
  • Rating points-4
AM

C++ - Test 005. Structures and Classes

  • Result:33points,
  • Rating points-10
Last comments
d
dblas5July 5, 2024, 9:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 7:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
Now discuss on the forum
F
FynjyJuly 22, 2024, 2:15 p.m.
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …
BlinCT
BlinCTJune 25, 2024, 11 a.m.
Нарисовать кривую в qml Всем привет. Имеется Лист листов с тосками, точки получаны интерполяцией Лагранжа. Вопрос, как этими точками нарисовать кривую? ChartView отпадает сразу, в qt6.7 появился новый элемент…
Evgenii Legotckoi
Evgenii LegotckoiJune 25, 2024, 1:11 a.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
BlinCT
BlinCTMay 5, 2024, 3:46 p.m.
Написать свой GraphsView Всем привет. В Qt есть давольно старый обьект дял работы с графиками ChartsView и есть в 6.7 новый но очень сырой и со слабым функционалом GraphsView. По этой причине я хочу написать х…
Evgenii Legotckoi
Evgenii LegotckoiMay 3, 2024, 12:07 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.

Follow us in social networks