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

Features of Django

Features of Django Offers High Security:- Django is super secure. To prove the feature, we can always take examples of lots of websites which are present worldwide and possess huge traffic. Django is secure because it covers the...

3 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.

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.

Django Tutorial

Django Introduction It is a web application framework written in a python programming language. It based on the MVT( Model View Templet) design pattern. It takes a short time to build an application...

2 minutes read.

Django vs Laravel

Django Overview Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison....

4 minutes read.

How to Uninstall Django from cmd

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Django Frontend

Django 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 front...

3 minutes read.

Django Logging

Every application developed has some bugs and errors. It is the responsibility of the developers to maintain the application by making it bug-free and error-free. To debug the application code...

5 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 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 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.

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.

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.

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 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...

3 minutes read.

Django Framework

Django is a popular high-level open-source web development Python framework based on follows Model View Template (MVT) architecture that allows rapid development. It. It provides common functionality like Admin Interface,...

3 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 Forms

Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison. It...

3 minutes read.

Django MVT

 MVT(Model View Template) MVT means Model View Template is a software design pattern The View is used to implement the business logic and to communicate with a model for data transmission and to...

2 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.