Evgenii Legotckoi
Evgenii LegotckoiMarch 15, 2017, 2:12 p.m.

Django - Tutorial 020. Adding articles pagination to the site using ListView and django-bootstrap3

In one of the previous articles , the option of introducing a page with articles pagination was shown, which can be the main page of the site, for example. In this case, django-bootstrap3 was used.

But if the page does not represent any special functionality, in addition to displaying the list of articles, for example, then you must use the generic classes. One of which is ListView . This will reduce the program code of the project and, accordingly, simplify it.

The ListView class allows you to specify a template that will be rendered to display the table, specify a data model or queryset that will need to be shown, as well as the number of objects per page that will be displayed when paginated.

IndexView

Let's recall how the previous View of the class looked to display the list of pages.

class IndexView(View):

    def get(self, request):
        context = {}
        # Taking all of the published article, sorted by date of publication
        all_articles = Article.objects.filter(article_status=True).order_by('-article_date')
        # Create Pagination, in which we send article and show,
        # that there will be 10 pieces on one page
        current_page = Paginator(all_articles, 10)

        # Pagination in django_bootstrap3 send response in this view:
        # "GET /?page=2 HTTP/1.0" 200,
        # So you need to pick up the page and try to pass it in Paginator, to find the page
        page = request.GET.get('page')
        try:
            # If there is, then choose this page
            context['article_lists'] = current_page.page(page)  
        except PageNotAnInteger:
            # If None, then select the first page
            context['article_lists'] = current_page.page(1)  
        except EmptyPage:
            # If you have gone beyond the last page, it returns the last
            context['article_lists'] = current_page.page(current_page.num_pages) 

        return render_to_response('home/index.html', context)

If you delete all comments, you still get lines 15. In addition, this is a separate class. And if there are many such View classes, then it can happen that each will have a duplicate code. That's why you need to use generics, such as ListView.

The same class inherited from ListView might look like this:

class IndexView(ListView):
    template_name = 'home/index.html'
    queryset = Article.objects.filter(article_status=True).order_by('-article_date')
    paginate_by = 10

Quite good, only 4 lines. But you can go even further and write everything at once in the urls.py file. And from the views.py file, you can remove IndexView .

from django.conf.urls import url
from django.views.generic import ListView

from knowledge.models import Article

app_name = 'home'
urlpatterns = [
    url(r'^$',
        ListView.as_view(
            template_name='home/index.html',
            queryset=Article.objects.filter(
                article_status=True,
            ).order_by(
                '-article_date'
            ),
            paginate_by=10
        ),
        name='index'),
]

django-bootstrap3

But when creating links pagination with django-bootstrap3 there is one nuance. The matter is that in the template bootstrap_pagination takes an object of type Page. And if in the old version we passed the object to the context, then ListView generates a normal QuerySet , which is not suitable for bootstrap_pagination. But still ListView passes in the context the object page_obj , which is just suitable for bootstrap_pagination .

Let's see what the home/index.html template looks like now.

{% extends 'home/base.html' %}
{% block page %}
    <h1>Publications</h1>
    {% if article_lists %}
        {% for article in object_list %}
            <article>
                <a href="{{ article.get_absolute_url }}">
                    <h2>{{ article.article_title }}</h2>
                </a>
                {{ article.desctription|safe }}
                <p><a class="btn btn-default btn-sm" href="{{ article.get_absolute_url }}">Читать далее</a></p>
            </article>
        {% endfor %}
    {% endif %}
{% load bootstrap3 %}
{% bootstrap_pagination page_obj %}
{% endblock %}

As you can see, there are two significant changes compared to the previous version:

  1. page_obj instead of article_lists в boostrap_pagination
  2. object_list instead of article_lists

However, ListView has a variable context_object_name , which is responsible for the variable name in the context, so you could leave article_lists .

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!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
e
  • ehot
  • April 1, 2024, 12:29 a.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

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

  • Result:46points,
  • Rating points-6
Last comments
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" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 8: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
a
a_vlasovApril 14, 2024, 4:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 12:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 2:47 p.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
AC
Alexandru CodreanuJan. 19, 2024, 10:57 p.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

Follow us in social networks