Class-based views are basically some pre-defined views that are bundled with django. These are reusable. Django developers felt that they have to write some common views for almost each application. So, they decided to create reusable views which results in Class-Based views. Class-based views (CBV) were introduced in Django 1.7.The reason behind this addition was that using inheritance it would be more customizable than a function-based view.


A table of class-based generic views of Django 3.1 is given below:
TypeClass NameDescription
BaseViewThis is the parent of all views. It performs dispatch and sanity checks.
BaseTemplateViewIt renders a template.
BaseRedirectViewIt redirects to any GET request.
DisplayListViewIt renders a queryset of items..
DisplayDetailViewIt brings details of  any item, by calling them with ‘pk’ or slug passed from a URL.
EditFormViewIt renders and processes a form.
EditCreateViewThis renders and processes a form for creating new objects. CreateView  and  FormView are pretty similar, except CreateView is more specific implementation of FormView.
EditUpdateViewUsed to update an object using a form.
EditDeleteViewIt renders and processes a form for deleting an object.
DateArchiveIndexViewThis renders a list of objects with a date field, the latest being the first
DateYearArchiveViewThis renders a list of objects on year given by URLConf.
DateWeekArchiveViewIt returns a list of objects on a year and week number.
Date DateMonthArchiveViewThis renders a list of objects on a year and month.
DateDayArchiveViewThis renders a list of objects on a year, month, and day.
DateTodayArchiveViewThis renders a list of objects on today’s date.
DateDateDetailViewThis renders an object on a year, month, and day identified by its ‘pk’ or ‘slug’.

We will discuss some of them here.

from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView

First we will have to import class-based views from generic. Now, Let’s start with DetailView.

Django DetailView

It returns details about an individual object of a model. We had a model named “Person”. Now, we will write a view to fetch data of an individual person from that model.

class PersonDetails(DetailView):
    model = Person
    template_name = 'details.html'

Here, we made a class and declared two class attributes named ‘model’ & ‘template_name’. They are descriptive enough to understand their work. Now make an URL in urls.py.

URL

path('person/<int:pk>/', PersonDetails.as_view(),name = 'person-detail-view'),

After running the server, let’s go to this link: “127.0.0.1:8000/person/id”

Output

Django ListView

ListView fetches multiple objects of a table in the database.

class AllPersonsView(ListView):
    model = Person
    template_name = 'persons.html'
    context_object_name = 'persons'

URL

path('all-persons/', AllPersonsView.as_view(),name='all-persons'),

Template

Output

CreateView

Create view is used to create new objects of a table. It is a little bit different to work with  than other class-based views. It renders a form where we put the required fields data of an object. So, firstly, we will make a form. We have created a forms.py file inside our app and added the code below.

forms.py

from django import forms
from .models import Person

class AddPersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields =('first_name', 'last_name', 'email',  'gender')

To create a form we have to inherit from django’s forms.ModelForm. In inner meta class we declared the model and it’s fields we want to take as inputs. Now it’s time to get back into View.

Views.py

from .forms import AddPersonForm

class AddPersonView(CreateView):
    form_class = AddPersonForm
    template_name = 'add-person.html'

Instead of ‘model’ attribute we declared ‘form_class’ here and assigned the “AddPersonForm”.

Template

This template is little bit different from other templates that we used so far. Here, we have used <form> tag and it is mandatory to put the ‘method’ attribute value = ‘POST’ as it will be  a ‘post’ request. Then, we used {% csrf_token %} (CSRF- Cross-Site Request Forgery ) Token which is an unique, secret and predictable value  used to ensure that only forms that have originated from a trusted domain can be used to POST data back. {{ form }} is the default name of django forms.

URL

path('add-person/', AddPersonView.as_view(),name = 'add-person'),

Output

If we go to  the link, django will show us the form. After filling up the form if we click the button ‘Person’ it will save the object in database.

After Saving,

We had 3 persons in our Person table. You can see Django has assigned the ‘person_id = 4’ dynamically…

+ posts

Author | Python-Django Developer

+ posts

Full-stack Developer (Python | Django | React | React-Native | Angular | Vue)