Evgenii Legotckoi
Jan. 8, 2018, 1:52 p.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

  1. class Index {
  2.  
  3. static initPaginator() {
  4. document.body.querySelectorAll('.pagination > li > a')
  5. .forEach( link => link.addEventListener('click', Index.pagination_link_clickHandler) );
  6. }
  7.  
  8. static pagination_link_clickHandler(event){
  9. event.preventDefault(); // prohibit an event
  10.  
  11. let path = event.target.href; // we take the path
  12. let page = Global.getURLParameter(path, 'page');
  13.  
  14. if (typeof page !== 'undefined') {
  15. jQuery.ajax({
  16. url: jQuery(this).attr('action'),
  17. type: 'POST',
  18. data: {'page': getURLParameter(path, 'page')}, // take the number of the page you want to display
  19.  
  20. success : function (json) {
  21.   // If the request was successful and the site returned the result
  22. if (json.result)
  23. {
  24. window.history.pushState({route: path}, "EVILEG", path); // set the URL in the browser string
  25. jQuery("#articles-list").replaceWith(articles); // We replace the div with a list of articles for a new one
  26. Index.initPaginator(); // Reinitialize the paginator
  27. jQuery(window).scrollTop(0); // Scroll the page to the top
  28. }
  29. }
  30. });
  31. }
  32. }
  33. }
  34.  
  35. 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.

  1. {% extends 'base.html' %}
  2. {% block page %}
  3. {% include 'article_previews_list.html' %}
  4. {% endblock %}
  5. {% block javascript_footer %}
  6. <script src="/static/js/index.js"></script>
  7. {% endblock %}

article_previews_list.html

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

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

urls.py

The route for the main page will look like this

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

views.py

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

  1. class IndexView(View):
  2. template_name = 'index.html'
  3.  
  4. def get(self, request):
  5. return render(request=request, template_name=self.template_name, context={'object_list': get_paginated_page(request, Article.objects.all())})
  6.  
  7. def post(self, request):
  8. if request.is_ajax():
  9. return JsonResponse({
  10. "result": True,
  11. "articles": render_to_string(
  12. request=request,
  13. template_name='article_previews_list.html',
  14. context={'object_list': get_paginated_page(request, Article.objects.all())}
  15. )
  16. })
  17. else:
  18. 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.

  1. # -*- coding: utf-8 -*-
  2.  
  3. from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
  4.  
  5.  
  6. def get_paginated_page(request, objects, number=10):
  7. current_page = Paginator(objects, number)
  8. page = request.GET.get('page') if request.method == 'GET' else request.POST.get('page')
  9. try:
  10. return current_page.page(page)
  11. except PageNotAnInteger:
  12. return current_page.page(1)
  13. except EmptyPage:
  14. return current_page.page(current_page.num_pages)

For Django I recommend VDS-server of Timeweb hoster .

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

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

Evgenii Legotckoi
  • Feb. 24, 2020, 2:54 p.m.

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

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