VOOZH about

URL: https://www.geeksforgeeks.org/python/listview-class-based-views-django/

⇱ ListView - Class Based Views Django - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

ListView - Class Based Views Django

Last Updated : 19 Nov, 2025

A ListView is a built-in class-based view used to show multiple records from a database. It handles data retrieval automatically, reducing the code required.

  • Specify the model from which the records will be fetched.
  • Django automatically retrieves all records of that model.
  • Define the template that will display the list.
  • The records are available in the template as object_list or a custom context name.

Example: Consider a project named 'geeksforgeeks' having an app named 'geeks'. After you have a project and an app, let's create a model of which we will be creating instances through our view.

In geeks/models.py:

After creating this model, we need to run two commands in order to create Database. 

Python manage.py makemigrations
Python manage.py migrate

Create instances of this model using the Django shell by running the following command in the terminal: 

Python manage.py shell

Enter following commands: 

>>> from geeks.models import GeeksModel
>>> GeeksModel.objects.create( title="title1", description="description1")
>>> GeeksModel.objects.create(title="title2", description="description2")
>>> GeeksModel.objects.create(title="title3", description="description3")

Now that the backend setup complete, verify that instances have been created by visiting: http://localhost:8000/admin/geeks/geeksmodel/ 

πŸ‘ django-listview-check-models-instances

To create a ListView, it is only necessary to specify the model. Django’s ListView will then look for a template named app_name/modelname_list.html. In this case, expected template path is geeks/templates/geeks/geeksmodel_list.html

In geeks/views.py:

Create a url path to map the view. In geeks/urls.py:

Create a template in templates/geeks/geeksmodel_list.html:

Visit http://localhost:8000/ to view the list of all model instances displayed through the Class-Based ListView.

πŸ‘ django-listview-class-based-views

Manipulate Queryset in ListView

By default, ListView displays all instances of a model in the order they were created. To modify the order or filter the results, get_queryset() method can be overridden.

In geeks/views.py:

Verify whether the instances are now displayed in reverse order.

πŸ‘ django-reverse-list-view-class

This approach allows complete control over the queryset, enabling modification, filtering or ordering as required.

Comment
Article Tags: