Open-Source Internship opportunity by OpenGenus for programmers. Apply now.
Django is a high-level open-source Python-based Web framework that provides rapid development with pragmatic design. Django often called Batteries-included framework as it provides built-in tools for many functionalities in a web application.
What are views?
Views are just a function that is callable each time a request is made to an application, it takes a request as an argument and returns a response.
Class-Based Generic Views are a superior set of Built-in views that are used for the implementation of selective view strategies such as Create, Retrieve, Update, Delete. It also allows you to structure your views and reuse code by harnessing inheritance and mixins.
Advantages of Class-based views over Function-based views:
- It allows you to organized code associated with specific HTTP methods (GET, POST, PUT, and DELETE) with separate methods instead of conditional branching.
- The concept of object-oriented paradigm can be applied such as inheritances, polymorphism, and mixins (multiple inheritances). That can be used to factor code into reusable components.
Topics discussed in this article is based on CRUD (Create, Retrieve, Update, Delete) functionality :
- CreateView :
- it can create and add new entries in the database.
- Retrieve Views :
- it is used to read, retrieve, search, or view existing entries as a ListView or retrieve any unique entry in detail by using DetailView
- UpdateView :
- it is used updates or edits existing entry
- DeleteView :
- it is used to delete or remove an existing entry
- FormView :
- it is used to render a form to a template
Let’s create a simple model for implementing Class-Based Generic Views
In your project create an app, and create a model by which we will be creating instances through our view. In app/models.py
from django.db import models
class userModel(models.Model):
# fields of the model
title = models.CharField(max_length = 200)
description = models.TextField()
# renames the instances of the model with their title name
def __str__(self):
return self.title
After creating this model, run migrations
python manage.py makemigrations
python manage.py migrate
Now, a form to render in template
Create a Django ModelForm for this model in your app folder, app/forms.py
from django import forms
from .models import userModel
# creating a form
class userForm(forms.ModelForm):
class Meta:
# specify model and field to be used
model = userModel
fields = '__all__'
Using Class-based Views
The class-based view enables us to respond to different HTTP request methods with different class instance methods, rather than with conditionally branching code(if-else/switch-case) inside a single view function.
code written in a function view would look something like:
from django.http import HttpResponse
def Index(request):
if request.method == 'GET':
return HttpResponse('openGenus')
where as same code written in class-based view look like:
from django.http import HttpResponse
from django.views import View
class Index(View):
def get(self, request):
return HttpResponse('openGenus')
CRUD (Create, Retrieve, Update, Delete) functionality of class-based view
-
CreateView
CreateView refers to a view used to create an instance of an object(entry) in the database. It is a view that displays a form for creating an entry in a database and redisplaying the form with validation errors and saving the object. By default it uses 'myapp/modelname_form.html' as a default template.
note: myapp is name of your app in django application
Example:
from django.views.generic.edit import CreateView
from .models import userModel
class userCreate(CreateView):
model = userModel
fields = ['title', 'description']
-
Retrieve Views ( ListView and DetailView)
- ListView
List View refers to a view that is used to display multiple instances of an entry in the database. By default it uses 'myapp/modelnamelist.html' as a default template. One specific model to create ListView Class-based ListView will automatically try to find a template in 'myapp/modelnamelist.html' and render entries. It also supports pagination.
Example:
from django.views.generic.list import ListView
from .models import userModel
class userList(ListView):
# specify model for list view
model = userModel
- DetailView
DetailView is the user to display one instance of an entry in the database. By default it uses 'myapp/modelnamedetail.html' as a default template.
Example:
from django.views.generic.detail import DetailView
from .models import userModel
class userDetailView(DetailView):
# specify the model to use
model = userModel
-
UpdateView
UpdateView refers to a view that is used to update a particular instance of an entry in the database with some extra details. By default it uses 'myapp/modelname_form.html' as a default template.
Example:
from django.views.generic.edit import UpdateView
from .models import userModel
class userUpdateView(UpdateView):
model = userModel
fields = [
"title",
"description"
]
''' we can specify success url to redirect after sucessfully updating details '''
success_url ="/"
-
DeleteView
DeleteView refers to a view that is used to delete a particular instance of an entry in the database. By default it tries to find 'myapp/modelname_confirm_delete.html' as a default template.
Example:
from django.urls import reverse_lazy
from django.views.generic.edit import DeleteView
from .models import userModel
class userDelete(DeleteView):
model = userModel
success_url = reverse_lazy('/')
-
FormView
FormView is used to display and verify Django Forms. Once specify which form to create and use. It tries to find template_name 'myapp/modelname_form.html', then Class-based FormView will automatically render that form. On error, redisplays the form with validation errors; on success, redirects to a new URL. It also includes functions with a feature to send mail and cleaning data.
Example:
from .forms import userForm
from django.views.generic.edit import FormView
class ContactView(FormView):
template_name = 'name.html'
form_class = userForm
success_url = '/'
def form_valid(self, form):
''' This method is called when valid form data has been POSTed. It should return an HttpResponse.'''
form.send_email()
return super().form_valid(form)
With this article at OpenGenus, you must have the complete idea of Class based Generic Views in Django. Enjoy.