Django: ListView and Paginagtion

Wasit Limprasert
2 min readMar 25, 2020

--

ListView

Coding

  1. [myproject/myapp/models.py] start with a simple model
from django.db import modelsclass Bike(models.Model):
start=models.DateField(auto_now=False, auto_now_add=True)
type=models.CharField(max_length=10)
price=models.DecimalField( max_digits=8, decimal_places=2)
def __str__(self):
return "Bike id:%s, start:%s type:%s price:%s"\
%(self.id,self.start,self.type,self.price)

2. [myproject/myapp/views.py] add ListView to views.py and we need Bike model and the tempalte “bike_list.html”

from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views.generic import ListView
from myapp.models import Bike
class BikeListView(ListView):
model = Bike
paginate_by = 3
#queryset=Bike.objects.filter(type='mountain')
template_name = 'bike_list.html'

3. [myproject/myapp/templates/bike_list.html] create a template files

<h2>Bikes</h2>
<ul>
{% for bike in object_list %}
<li>{{bike}}</li>
{% endfor %}
</ul>
<div class="pagination">
{% if page_obj.has_previous %}
<a href="?page=1">[<<]</a>
<a href="?page={{page_obj.previous_page_number}}">[<]</a>
{% endif %}
[{{page_obj.number}}/{{page_obj.paginator.num_pages}}] {% if page_obj.has_next %}
<a href="?page={{page_obj.next_page_number}}">[>]</a>
<a href="?page={{page_obj.paginator.num_pages}}">[>>]</a>
{% endif %}
</div>

4. [myproject/myproject/urls.py] add BikeListView to urls.py

from django.contrib import admin
from django.urls import path
from myapp.views import BikeListView
urlpatterns = [
path('admin/', admin.site.urls),
path('bikes/', BikeListView.as_view(),name='bikes'),
]

5. [myproject/myproject/settings.py]

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]

Results

--

--

Wasit Limprasert
Wasit Limprasert

Written by Wasit Limprasert

Wasit Limprasert is at Thammasat University, PhD in Computer Science from Heriot-Watt University. Specialist in Big Data, Deep Learning and Knowledge Graph.

No responses yet