Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Views in Django are Python functions or classes that receive a web request and return a web response in the Django framework. A basic HTTP response, an HTML template response, or an HTTP redirect response that transfers a user to another page are all possible responses. Django views provide the logic required to return information to the user in any manner. The logic that deals with views should be kept in the ‘views.py’ file as a best practice in a Django app.
The list view accesses the database to create a list of model elements. A Django list view is a sort of view that displays the elements/instances of a table in a database. This is used to display the many entries in the database.
What is class-based List View?
Class-based list View in Django is a view (logic) that allows you to list all or specific instances of a table from the database in a particular order. It shows various data on a single page or view, such as products on an e-commerce site. Django provides exceptional List View functionality.
This blog focuses on the class-based list view in Django, which includes Django Models. We will work on a project with models and multiple instances to display the class-based List View.
When to use class-based List View?
Django includes several generic views based on classes to help with common tasks. List View is one of them.
So, we should use List View when we wish to display or view a list of objects on an HTML page.
List View should not be used when our page has forms and creates or updates objects. Form View, Create View, and Update View are better for working with forms, object creation, and object updation.
Sample Django App
Consider that we are working on a library project. We will have a Book model in the ‘store’ application.
# store/models.py
# To import the Django model
from django.db import models
# To declare the new model having name 'Book'
class Book(models.Model):
# The fields of the 'Book' model
name = models.CharField(max_length=255)
isbn_number = models.CharField(max_length=13)
class Meta:
db_table = 'book'
# To rename the instances of the 'Book' model with the title name
def __str__(self):
return self.name
After creating this model, we'll need to run two commands to establish a database.
Now, using shell, let's make some instances of this model, run from bash.
python manage.py shell
Now, we'll make a list of all of the Book objects to be stored in the database. We will be using List View to create a new view called BookListView that has pagination functionality.
# store/views.py
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
# specific to this view
from django.views.generic import ListView
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from .models import Book
@method_decorator(login_required, name='dispatch')
class BookListView(ListView):
model = Book
template_name = 'book/list.html'
context_object_name = 'books'
paginate_by = 5
def get_context_data(self, **kwargs):
context = super(BookListView, self).get_context_data(**kwargs)
books = self.get_queryset()
page = self.request.GET.get('page')
paginator = Paginator(books, self.paginate_by)
try:
books = paginator.page(page)
except PageNotAnInteger:
books = paginator.page(1)
except EmptyPage:
books = paginator.page(paginator.num_pages)
context['books'] = books
return context
We can see in the above code that we are overriding the get_context_data to provide pagination support by sending in an extra query parameter called a page.
In store/urls.py, we'll add a URL for BookListView.
# store/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('book', views.BookListView.as_view(),
name='book-list'),
]
We need to ensure that the project URLs include the store app URLs. Otherwise, we will include it.
# project/urls.py
from django.urls import include, path
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('store/', include('store.urls')),
]
The template code has to be written. We're using Bootstrap v4 and have a '__base.html' as the base template from which we extend all of our other templates. The '__base.html' looks like:
Our first ListView with a Class-Based View is now complete. After logging in as admin, we added 6 books.
Output(as Admin)
Therefore, the store now has five books on page 1 and the last one on the next page, as shown below.
Output(as User)
Frequently Asked Questions
What are views in Django?
Ans: Views in Django are an essential feature of the Django MVT(Model-View-Template) Structure. According to the Django documentation, a view function is a Python function that takes a Web request and delivers a Web response. This response could be the HTML content of a Web page, a redirect, a 404 error, an XML document, an image, or anything else that a web browser can display.
2. How many forms of list views does Django have?
Ans: Function-based list views and class-based list views are the two forms of list views in Django.
3. Why is list view preferred over template view?
Ans: Template view can do everything list view can however, list view has the advantage of not requiring as much boilerplate code as template view would.
List view would save us several lines of code while also providing better separation of concern.
Key Takeaways
In this blog, we have learned the concepts of class-based list views in Python, which generates a list of model items from the database. Views are crucial for web development, especially when utilizing MVT(Model View Template) frameworks like Django. This essential ability is beneficial for Python developers who work as Django developers, backend engineers, or full-stack engineers. Filtered items can also be displayed or ordered in numerous ways based on specific criteria in List View.
Go through The Basics of Django Framework to deeply understand the concept of Django to get a hold of the class-based list view in Django.