How do I use pagination with Django class based generic ListViews?

django pagination bootstrap
django pagination limit page range
django pagination with search
django listview
django-filter pagination
django-cursor pagination
'paginator' object has no attribute 'get_page'
pagination in django rest framework

How do I use pagination with Django 1.3?

The documentation is not very clear on this.

  • What goes to my views.py?

  • What goes to my template?

  • What goes to my URLconf file?

I think you ask for information about using pagination with the new class based views since, with traditional function based views, it is easy to find. I found that just by setting the paginate_by variable is enough to activate the pagination. See in Class-based generic views.

For example, in your views.py:

import models
from django.views.generic import ListView

class CarListView(ListView):
    model = models.Car      # shorthand for setting queryset = models.Car.objects.all()
    template_name = 'app/car_list.html'  # optional (the default is app_name/modelNameInLowerCase_list.html; which will look into your templates folder for that path and file)
    context_object_name = "car_list"    #default is object_list as well as model's_verbose_name_list and/or model's_verbose_name_plural_list, if defined in the model's inner Meta class
    paginate_by = 10  #and that's it !!

In your template (car_list.html), you can include a pagination section like this (we have some context variables available: is_paginated, page_obj, and paginator).

{# .... **Normal content list, maybe a table** .... #}
{% if car_list %}
    <table id="cars">
        {% for car in car_list %}
            <tr>
                <td>{{ car.model }}</td>
                <td>{{ car.year }}</td>
                <td><a href="/car/{{ car.id }}/" class="see_detail">detail</a></td>
            </tr>
        {% endfor %}
    </table>
    {# .... **Now the pagination section** .... #}
    {% if is_paginated %}
        <div class="pagination">
            <span class="page-links">
                {% if page_obj.has_previous %}
                    <a href="/cars?page={{ page_obj.previous_page_number }}">previous</a>
                {% endif %}
                <span class="page-current">
                    Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
                </span>
                {% if page_obj.has_next %}
                    <a href="/cars?page={{ page_obj.next_page_number }}">next</a>
                {% endif %}
            </span>
        </div>
    {% endif %}
{% else %}
    <h3>My Cars</h3>
    <p>No cars found!!! :(</p>
{% endif %}
{# .... **More content, footer, etc.** .... #}

The page to display is indicated by a GET parameter, simply adding ?page=n, to the URL.

Pagination | Django documentation, Under the hood, all methods of pagination use the Paginator class. It does from django.views.generic import ListView from myapp.models import Contact class  The two following generic class-based views are designed to display data. On many projects they are typically the most commonly used views. class django.views.generic.detail.DetailView ¶ While this view is executing, self.object will contain the object that the view is operating upon. Ancestors (MRO) This view inherits methods and attributes

assume, I have a class in app/models.py named FileExam(models.Model):

app/models.py

class FileExam(models.Model):
    myfile = models.FileField(upload_to='documents/%Y/%m/%d')
    date = models.DateTimeField(auto_now_add=True, blank=True)
    teacher_name = models.CharField(max_length=30)
    status = models.BooleanField(blank=True, default=False)

app/views.py

from app.models import FileExam
from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger

class FileExamListView(ListView):
    model = FileExam
    template_name = "app/exam_list.html"
    paginate_by = 10


    def get_context_data(self, **kwargs):
        context = super(SoalListView, self).get_context_data(**kwargs) 
        list_exam = FileExam.objects.all()
        paginator = Paginator(list_exam, self.paginate_by)

        page = self.request.GET.get('page')

        try:
            file_exams = paginator.page(page)
        except PageNotAnInteger:
            file_exams = paginator.page(1)
        except EmptyPage:
            file_exams = paginator.page(paginator.num_pages)

        context['list_exams'] = file_exams
        return context

only a a little change in the get_context_data and added pagination code from django documentation here

app/templates/app/exam_list.html

normal content list

<table id="exam">
  {% for exam in list_exams %}
  <tr>
    <td>{{ exam.myfile }}</td>
    <td>{{ exam.date }}</td>
    <td>.....</td>
  </tr>
  {% endfor %}
</table>

paginate section

{% if is_paginated %}
<ul class="pagination">
{% if page_obj.has_previous %}
    <li>
        <span><a href="?page={{ page_obj.previous_page_number }}">Previous</a></span>
    </li>
{% endif %}
    <li class="">
        <span>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.</span>
    </li>
{% if page_obj.has_next %}
    <li>
        <span><a href="?page={{ page_obj.next_page_number }}">Next</a></span>
    </li>
{% endif %}
</ul>
{% else %}
    <h3>Your File Exam</h3>
    <p>File not yet available</p>
{% endif %}

app/urls.py

urlpatterns = [
url(
    r'^$', views.FileExamListView.as_view(), name='file-exam-view'),
), 
... ]

How to Paginate with Django, In this tutorial I will show how to paginate data using function based views and how to paginate using class-based views (ListView). When to use ListView? Django provides several class based generic views to accomplish common tasks. One among them is ListView. Most basic class based generic view is TemplateView. We wrote about it in our last post. ListView should be used when you want to present a list of objects in a html page.

We have 2 methods to do this.

First one is simple and just set the class field paginate_by. Nothing need we to do with get_context_data method.

The second method is a little complicated but we can gain more comprehension about pagination and customize complex pagination or several pagination. Let's see it.

It can be done in three steps.

1.Override get_context_data method of your View.

Pass page_keys and pages so that we can iterate the lists and avoid hard-coding .

def get_context_data(self, *, object_list=None, **kwargs):
    context = super().get_context_data()
    df = pd.DataFrame(list(self.model.objects.all().values()))
    ipc = df.groupby('ip')['ip'].count().sort_values(ascending=False)
    urlc = df.groupby('url')['url'].count().sort_values(ascending=False).to_dict()

    ipc = tuple(ipc.to_dict().items())
    urlc = tuple(urlc.items())

    pages = []
    page_keys = ['page1', 'page2']
    for obj, name in zip([urlc, ipc], page_keys):
        paginator = Paginator(obj, 20)
        page = self.request.GET.get(name)
        page_ipc = obj
        try:
            page_ipc = paginator.page(page)
        except PageNotAnInteger:
            page_ipc = paginator.page(1)
        except EmptyPage:
            page_ipc = paginator.page(paginator.num_pages)
        pages.append(page_ipc)

    context['data'] = zip(pages, page_keys)
    return context
2.Customize your sub template.

We define some variables so we can iterate through the pagination list.

pagination.html

    {% if is_paginated %}
        <ul class="pagination">
        {% if page_obj.has_previous %}
            <li>
            <span><a href="?{{ pname }}={{ page_obj.previous_page_number }}">Previous</a></span>
            </li>
        {% endif %}
        <li class="">
            <span>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.</span>
        </li>
        {% if page_obj.has_next %}
            <li>
            <span><a href="?{{ pname }}={{ page_obj.next_page_number }}">Next</a></span>
            </li>
        {% endif %}
        </ul>
    {% else %}
        <h3>Your File Exam</h3>
        <p>File not yet available</p>
    {% endif %}
3.Customize outer template.

index.html

{% for foo,name in data %}
    <div class="col-md-3 table-responsive">

            {% for k,v in foo %}
                <tr>
                    <th>{{ forloop.counter }}</th>
                    <td>{{ k }}</td>
                    <td>{{ v }}</td>
                </tr>
            {% endfor %}

        {% include 'pagination.html' with pname=name  page_obj=foo %}
    </div>
{% endfor %}

Django Tutorial Part 6: Generic list and detail views, The final part of the tutorial will demonstrate how to paginate your data when using generic class-based list views. Book list page. The book list  So on the page, 3 items should be showing, and pagination should take me to the the next set of 3. The html is showing, and when I click the links it is taking me 2 page 2. The problem is the fact that 6 items are showing, and not 3, and when I go to page 2, there are the same 6 items there.

Django Class Based Views Pagination with Bootstrap 4, Django Class Based Views Pagination with Bootstrap 4. Posted in Thus, if you use ListView , for example, using pagination can give us results like this: (docs)​which is a class ListView generic list class inherits from. In Django 2.2 you can do this (it works fine at least with a get-request): from django.views.generic import ListView from django.views.generic.edit import FormMixin from .models import Property from .forms import SearchForm class ListPageView(FormMixin, ListView): template_name = 'property_list.html' model = Property form_class = SearchForm

Generic views, This application provides a customized class-based view, similar to django.views​.generic.ListView, that allows Ajax pagination of a list of objects (usually a  Instead, however, we're going to use a class-based generic list view (ListView) — a class that inherits from an existing view. Because the generic view already implements most of the functionality we need and follows Django best-practice, we will be able to create a more robust list view with less code, less repetition, and ultimately less maintenance.

Generic views, This application provides a customized class-based view, similar to django.views​.generic.ListView, that allows Ajax pagination of a list of objects (usually a  Django provides high-level and low-level ways to help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links. The Paginator class ¶ Under the hood, all methods of pagination use the Paginator class. It does all the heavy lifting of actually splitting a QuerySet into Page objects.

Comments
  • Thats ok, but how do you tie the template too see the "car_list" object?
  • FYI you can also do this directly in urls.py:url(r'^cars/$', ListView.as_view( model=Car, paginate_by=10 )),
  • lesson I learned: to find a method, open all ancestor classes in new tabs, and CTRL+F away the key word. so from docs.djangoproject.com/en/dev/ref/class-based-views/…, which we know exists from the basic tutorial, open all Ancestors links and search for "pagi"
  • I have been doing this, but the problem I find, is when I do extra processing on objects in the queryset, it applys them to all of the results in the database. So for a query that returns 100 objects, but shows only ten objects per page, the extra processing will be done on 100 objects.
  • I don't like the hardcoded urls you can replace it with: <a href="?page={{ page_obj.previous_page_number }}">previous</a>
  • This doesn't look right: context = super(SoalListView, self).... Did you mean: context = super(FileExamListView, self)...?