Evgenii Legotckoi
Evgenii LegotckoiJan. 8, 2018, 2:52 a.m.

Django - Tutorial 031. Change URL without reloading the page with partial content loading

The less information a site has to transmit to each request, the better. Because we get less load on the server and on the communication channel. The first such improvement on the site I did was loading the list of articles when navigating the page paginator.

The point is that when the user wants to go to the next page with a list of articles and clicks on the link in the paginator , the click event is intercepted, the event is canceled, but the AJAX request is sent to the server with the number of the requested page. When the server receives such a request, it only renders the list of articles and sends it back.


Replace the URL in the browser without reloading the page

For the main page of the site I created a JavaScript file index.js, which will contain the logic of the AJAX request, as well as the binding of the click handler to the links in the paginator. An important point is that I use django-bootstrap3 for the paginator. Accordingly, to connect the click handler, I use the '.paginator> li> a' selector.

The contents of the file will be as follows

class Index {

    static initPaginator() {
        document.body.querySelectorAll('.pagination > li > a')
                .forEach( link => link.addEventListener('click', Index.pagination_link_clickHandler) );
    }

    static pagination_link_clickHandler(event){
        event.preventDefault(); // prohibit an event

        let path = event.target.href; // we take the path
        let page = Global.getURLParameter(path, 'page');

        if (typeof page !== 'undefined') {
            jQuery.ajax({
                url: jQuery(this).attr('action'),
                type: 'POST',
                data: {'page': getURLParameter(path, 'page')}, // take the number of the page you want to display

                success : function (json) {
                    // If the request was successful and the site returned the result
                    if (json.result)
                    {
                        window.history.pushState({route: path}, "EVILEG", path); // set the URL in the browser string
                        jQuery("#articles-list").replaceWith(articles); // We replace the div with a list of articles for a new one 
                        Index.initPaginator(); // Reinitialize the paginator
                        jQuery(window).scrollTop(0); // Scroll the page to the top
                    }
                }
            });
        }
    }
}

Index.initPaginator();

I try to use the standard ecmascript 6. Therefore, for the index page, the Index class is used to generalize the methods used.

To get the page number in the URL, use the getURLParameter function.

Template structure

So we need to have a special template structure, namely, there must be a template for rendering the list of articles, in my case a template with a preview of one article, as well as a template for the main page of the site.

That is, it will be:

  • article_preview.html - This template will not be considered, since it is not of interest to us in this case
  • article_previews_list.html
  • index.html

index.html

index.html is inherited from the base template base.html in which there is a block for connecting javascript files.

{% extends 'base.html' %}
{% block page %}
    {% include 'article_previews_list.html' %}
{% endblock %}
{% block javascript_footer %}
    <script src="/static/js/index.js"></script>
{% endblock %}

article_previews_list.html

The list of articles is a div that will be replaced with each request.

<div id="articles-list">
    {% load bootstrap_pagination from bootstrap3 %}
    {% for article in object_list %}
        {% include 'knowledge/article_preview.html' %}
    {% endfor %}
    {% bootstrap_pagination object_list pages_to_show="10" %}
</div>

urls.py

The route for the main page will look like this

urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index')
]

views.py

And now consider a view that will return a list of articles or just a whole page

class IndexView(View):
    template_name = 'index.html'

    def get(self, request):
        return render(request=request, template_name=self.template_name, context={'object_list': get_paginated_page(request, Article.objects.all())})

    def post(self, request):
        if request.is_ajax():
            return JsonResponse({
                "result": True,
                "articles": render_to_string(
                    request=request,
                    template_name='article_previews_list.html',
                    context={'object_list': get_paginated_page(request, Article.objects.all())}
                )
            })
        else:
            raise Http404()

An important point is that the site must correctly process both types of requests, both normal and AJAX requests. Since the user can go directly to one of the pages, and through the pagination on the site.

Perhaps in this code you will be interested in the get_paginated_page method, which uses the Paginator class to generate the page you want to display.

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

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage


def get_paginated_page(request, objects, number=10):
    current_page = Paginator(objects, number)
    page = request.GET.get('page') if request.method == 'GET' else request.POST.get('page')
    try:
        return current_page.page(page)
    except PageNotAnInteger:
        return current_page.page(1)
    except EmptyPage:
        return current_page.page(current_page.num_pages)

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!

B
  • Feb. 24, 2020, 12:37 a.m.

Евгений Здравствуйте! Не могу понять вот эту часть кода: url: jQuery(this).attr('action')
наверное здесь должен быть путь к url, тогда 'action' на какой url указывает?

Evgenii Legotckoi
  • Feb. 24, 2020, 3:54 a.m.

Добрый день. Там будет url, на который указывает ссылка тега a в пагинаторе, если правильно помню )) Написал этот код и забыл.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 10:56 a.m.

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

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 10:45 a.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 10:35 a.m.

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

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 9, 2024, 12: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, 4: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, 2: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" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 3:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
BlinCT
BlinCTMay 5, 2024, 11:46 a.m.
Написать свой GraphsView Всем привет. В Qt есть давольно старый обьект дял работы с графиками ChartsView и есть в 6.7 новый но очень сырой и со слабым функционалом GraphsView. По этой причине я хочу написать х…
BlinCT
BlinCTMay 5, 2024, 11:44 a.m.
добавить qlineseries в функции Давно я не работал с виджетами и с формами, на мой взгляд уже пережитов, и в управлении не очень удобное это все. Н оя у вас не увидел в коде где вы QCharts растягиваете на область парента.…
PS
Peter SonMay 3, 2024, 11:57 p.m.
Best Indian Food Restaurant In Cincinnati OH Ready to embark on a gastronomic journey like no other? Join us at App india restaurant and discover why we're renowned as the Best Indian Food Restaurant In Cincinnati OH . Whether y…
Evgenii Legotckoi
Evgenii LegotckoiMay 2, 2024, 8:07 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.
IscanderChe
IscanderCheApril 30, 2024, 10:22 a.m.
Во Flask рендер шаблона не передаётся в браузер Доброе утро! Имеется вот такой шаблон: <!doctype html><html> <head> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_…

Follow us in social networks