Django Class Based Views

Class-based views were developed to solve the problem of customizing function-based generic views. We can arrange our view code Object-Oriented by using class views. Class-based views do more than function-based views. A request is passed to a class-based view as an argument, and it gets returned as a response. They allow structuring views better in the code. There are some advantages and differences of class-based views compared to function-based views.

The structure of code to process HTTP requests like getting and POST is different in both of them.  The function-based view for handling GET and PUT requests might look something like this.

# views.py
def function_based_view(request):
	if request.method == ‘GET’:
		#Handle get request
	If request.method == “PUT”
		#Handle Put request

The same code for class-based view will be:

from Django. views import View


class Class_Based_View(View):
    def get(self, request):
        ...  # Handle Get reuqest


    def put(self, request):
        ...  # Handle Put request

We have to modify urls.py also

# urls.py
from Django.urls import path
from project.views import Class_Based_View


urlpatterns = [
    path('about/', Class_Based_View.as_view()),
]

With the help of Class-Based Views, we can use multiple inheritance techniques to make the code reusable.

The generic class-based view is a type of class-based view that provides some extra function in class-based view. For example, the Template view is the generic class-based view that generates and sends context to the class-based view.

Using Class-based Views

Django uses an URL resolver to handle the HTTP requests. Since URL resolver expects to send the request through a function, not from a class and in class-based views, we are doing it through a class, so class-based views have a class called ­as_view ()­ which returns a function that is used to process various HTTP requests.

The operation of this returned function depends on various methods. First, this function creates an instance of this class and then calls setup() and dispatch() to initialize attributes and recognize the type of request.

The class-based views are generated from the parent class view. There are three important methods by which view class comprises.

  • __init__: The __init__ method can be found in most classes. It is used to set arguments as attributes.
  • Dispatch: The dispatch takes a request and recognizes the type of request for, e.g., GET, PUT, POST, etc., and returns the result.
  • As_view: This method creates and returns a new function.

Mixins

In Mixins, we can combine multiple behaviors and attributes. It is a type of multiple inheritances. Class-based views includes various mixins for example, TemplateResponseMixin, which is used to define the method render_to_response(). They are very helpful in reusing the code in different classes. But it also has some side effects like if we use more mixins, it will become harder to read the child class and its functions.

Template View

The template view is the class-based view that provides a reusable generic class-based view based on context data and rendering template.

class TemplateView(TemplateResponseMixin, ContextMixin, View):
    ...
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)

Generic Class-based Views

Generic class-based views are introduced to solve common problems such as handling form, list views, creating new objects, etc. Also, by using the generic class-based views, the development process gets faster.

There are many views available in generic views.

Simple Generic Views

  • Template View
  • Redirect View
  • View

List Views

  • List View

Date Views

  • YearArchiveView
  • DayArchiveView
  • MonthArchiveView
  • WeekArchiveView
  • TodayArchiveView
  • DateDetailView

Editing Views

  • CreateView
  • UpdateView
  • DeleteView
  • FormView

Forms in Class-based View

An example of handling forms in class-based view is:

frommyapp.forms import ValidationForm
fromDjango.views.generic.edit import FormView


classValidationFormView(FormView):
template_name = 'form.html'
form_class = ValidationForm
success_url = '/success/'


defform_valid(self, form):
        # This gets called after POST of data
        # It should return an HttpResponse.
form.send_email()
return super().form_valid(form)

Related Topics

Uses of Django

Django is a free and open-source Python-based web framework, which offers great functionalities to its users. Django was developed in 2003, and the final version was released in 2008 by...

3 minutes read.

Django Admin

To manage the content of the website, e.g., adding and deleting posts, web developers need an admin portal on the website. The admin portal allows trusted users, also knows as...

3 minutes read.

Django CMS vs WordPress

Both Django CMS and WordPress belong "Self-Hosted Blogging" or "Content Management System (CMS)" category, that is used to manage digital content. Bloggers usually use these platforms. Django CMS Django is one of...

4 minutes read.

Django CMS

Django is one of the most popular open-source Python web development framework. Developers use Django to build a website from scratch. Like WordPress, Django CMS is also a Content Management...

9 minutes read.

Django Messages

Django Framework Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

6 minutes read.

Django and React

This article will discuss the overview of Django and React, their advantages, applications, and most importantly, how to implement react in Django. What is Django? Django is a free and open-source web...

6 minutes read.

How to Implement Multiple User Types with Django

Django Framework: Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

3 minutes read.

Django Stack

Django is a popular Python web application framework that adheres to the "batteries-included" tenet. Batteries-guiding included idea is that common functionality for creating web applications should be provided with the...

5 minutes read.

Django Create Superuser

For managing the website, we need an Admin while creating the Django application. In order to create the admin user, create superuser command is used. The superuser is called the...

3 minutes read.

Django CSRF

Django is a high-level python based web framework. Django is open source and free to use for all. Django provides many features to web developers like scalability, security, rapid development,...

4 minutes read.

Django Create Project

Django is an open-source free to use web framework which is based on Python. Django uses Model-View-Template as its architecture. The final version of Django was released in 2008. Django...

4 minutes read.

Django Image Upload

Django is a python based web framework that uses Model View Template as its architecture. Django provides really quick web development with its functionalities. While we are building a website,...

3 minutes read.

How to connect Django with Mysql

Any web application contains some data that comes from the input of the end-users. Thus, the database is required to handle those data. Several databases could be used to connect...

3 minutes read.

Django Celery

Django is a python-based web framework. It is an open-source and free-to-use framework. Django uses the Model View Template architecture. Django provides many functionalities to web developers. One of these...

3 minutes read.

Django Filters

Django is a high-level python based web framework. Django is mostly used as a backend engine for websites. Nowadays, every website communicates to a database to fetch all the information...

3 minutes read.

Life Cycle of Django

Life Cycle of Django Request - Response life cycle in Django  Thebasic principle of http protocol is the client sends a request to the server based on the request data, and the server sends...

3 minutes read.

Django Pagination

Django is an open-source free to use python based web framework. Django provides many inbuilt tools for web developers to provide rapid web development. One of these tools is pagination....

4 minutes read.

Creating View in Django

Creating View in Django    Django views are a key component of the frameworkbased applications.We are using Python function or class at their simplest, which takes up a web query and returns a web response.Views are used to get objects from the server, change objects if needed, render types, return HTML, and much more. Class Based View and Function based Django has two types of views: views based on functions (FBVs) and views based on class (CBVs).Initially, Django began with only FBVs, but then introduced CBVs as a way to model features so we didn't have to write boilerplate (i.e. the same software) code again and again.CBVs would be a way to increase efficiency, so you don't have to write as much code as you can. CBVs are classes of Python at their heart. Django ships with a range of "model" CBVs with pre-configured features that can be reused and often expanded.Then helpful names are given to these classes that explain what kind of functionality they provide.These are often referred to as "universal views" because they provide solutions to specific needs. The classes have a journal View function, or "view" for short, is simply a Python program that uses a web query and returns a web response. This response may include the HTML content of a web page, or a redirect, or a 404 error, or an XML file, or an image, etc. Example: You use a view to create a web page, remember that you need to connect a view to a URL to see it as a web page. Simple View We will create a simple view in myapplication to say “Welocome to django application” See the following view – from django.http import HttpResponse ...

4 minutes read.

Django Create App

Django is a Python-based web framework that is based on the Model View Template architecture. In this post, we will go through the installation and setup for our first Django...

4 minutes read.

Django Model Fields

In Django, if we want to store the information about anything, we use Models. It contains various fields about the data. Generally, each model represents a database where all the...

4 minutes read.