Django - Tutorial 024. Polling with AJAX

AJAX, Django, Polling

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 .

10% refund of hotel reservation amount on Booking
10% refund of hotel reservation amount on Booking
We offer a link with a 10% return on the amount of the order when booking a hotel through Booking
Support the author Donate
d

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Looking for a Job?
14,000.00 руб. - 40,000.00 руб.
Разработчик Qt
Annino, Moscow Oblast, Russia
5,000.00 руб. - 15,000.00 руб.
Дизайнер
Moskovskiy, Moscow, Russia
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

A
Aug. 22, 2019, 11:24 p.m.
Aleksandr73

Qt - Test 001. Signals and slots

  • Result:47points,
  • Rating points-6
Aug. 21, 2019, 10:23 a.m.
Andrej Ermoshin

C++ - Test 002. Constants

  • Result:58points,
  • Rating points-2
Aug. 21, 2019, 10:15 a.m.
Andrej Ermoshin

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

  • Result:86points,
  • Rating points6
Last comments
Aug. 19, 2019, 7:41 a.m.
Andrej Jankovich

это проблема дистрибутива, попробуйте установить через пакетный менеджер snap Суть проблемы: libQt5Core которая лежит в дистрибутиве требует версию glibc >= 2.25 у вас видимо …
b
Aug. 18, 2019, 6:09 a.m.
bbb116

cqtdeployer /home/aleks/CQtDeployer/bin/cqtdeployer: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.25' not found (required by /home/aleks/CQtDeployer/lib/libQt5Core.so.5) linux mint …
D
Aug. 17, 2019, 9:04 a.m.
Damir

github ChekableTView Правой групповая смена значения при перетаскивании левой как обычно.
Aug. 16, 2019, 1:03 p.m.
Evgenij Legotskoj

Потому, что в минуте 60 секунд
Aug. 16, 2019, 12:16 p.m.
Dmitrij

а почему делитель 60000, а не 1000?
Now discuss on the forum
Aug. 24, 2019, 7:21 a.m.
Evgenij Legotskoj

Не помню, давно уже с QML не работал, по-моему, обычно пишет в консоль, что не находит файл. В любом случае какую-то ошибку в консоль выкидывает. Но если честно, если у вас проект будет ак…
BG
Aug. 24, 2019, 4:27 a.m.
Brjus Gliff

Спасибо, вначале в документации было не понятно что к чему, теперь разобрался
I
Aug. 21, 2019, 8:36 a.m.
Intruder

Александр, мне не нужно перебирать. Вы говорите правильно, сначала я написал избыточный код просто не подумав. Задача такая, мне нужно просто переложить из QMap в атрибуты xml тега все, что там …
Aug. 21, 2019, 3:16 a.m.
nayk1982

Если Вы разрабатываете какую-то универсальную утилиту, которая вообще не привязана к логике, тогда как вариант: 1. Получить список таблиц через QSqlDatabase::tables 2. Для каждой табли…
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB