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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…