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 .

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
d

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

Comments

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
Donate

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

PayPalYandex.Money
Timeweb

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
AS
May 26, 2020, 11:29 a.m.
Artem Sun-Dun-Chan

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

  • Result:50points,
  • Rating points-4
MN
May 25, 2020, 11:33 a.m.
Mitja Nagibin

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

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

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

  • Result:66points,
  • Rating points-1
Last comments
AL
May 29, 2020, 5:24 a.m.
Aleksandr Leonidov

Django - Tutorial 036. How to add authentication through social networks. VKontakte

Здравствуйте! После клика на ссылку авторизации выдает json словарь с ошибкой: {"error":"invalid_request","error_description":"redirect_uri is incorrect, check application redirect uri in …
May 28, 2020, 3:14 p.m.
Evgenij Legotskoj

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

Ну в моём примере, который в статье сработало так model->setData(model->index(1, 1), 7); Поскольку model->index(1, 0) - это индекс колонки id, которая скрыта, поэтому…
MA
May 28, 2020, 3:08 p.m.
Mihail A

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

Спасибо, завтра првоерю. А model->setData(model->index(1, 0), 7); Тоже заработало?
May 28, 2020, 3:06 p.m.
Evgenij Legotskoj

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

Да, метод data всё-таки влиял, я переписал его так и заработало удаление QVariant TableModel::data(const QModelIndex &idx, int role) const{ if (role == Qt::BackgroundColorRole) {…
May 28, 2020, 2:49 p.m.
Evgenij Legotskoj

Django - Tutorial 011. Adding comments to the site based on Django

Он более функциональный и его функционал объективно лучше поддерживается Django. Из первого, что приходит на ум: Это наличие полей типа Array Поддержка полей для JSON …
Now discuss on the forum
IP
May 29, 2020, 1:55 a.m.
Igor' Poroshin

QTablwView + QSqlQueryModel скрыть пустой столбец

Да, понятно. В данном случае лучше использовать серверную процедуру (если такие поддерживаются), в которой будет проверяться наличие всех пустых строк у нужного столбца и вызываться соответ…
RG
May 28, 2020, 6:21 p.m.
Rovshan Gurbanov

Сборка под старые версии Android

У меня SDK почти все версии есть, NDK есть версии 10, 17, 21. Но собирается приложение только с NDK v21 под Android версии 7.0 и выше Версия Qt у меня 5.14.2
May 28, 2020, 7:58 a.m.
Evgenij Legotskoj

Освобождение памяти QMainWindow::setCentralWidget

Да, соглашусь. Просто удаление происходит позже, а не сразу.
May 28, 2020, 5:43 a.m.
Mihailll

При подключении к git как указать пароль?

Нужно сделать ssh-keygen и потом полученый из файла код скопировать в ssh ключ в бикбакете
F
May 28, 2020, 1:42 a.m.
Fidan

QML

Да, проблема ушла, спасибо.
About
Services
© EVILEG 2015-2020
Recommend hosting TIMEWEB