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

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

Django Project

Django Project Let's start to use it. Each web app you want to build in Django is called a project; and a project is a collection of apps. A software is a series of...

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.

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 Environment Setup

Django is a free and open-source web framework, which uses Python as its programming language. It is based on Model View Template (MVT) architecture. A framework is a collection of...

4 minutes read.

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 Authentication

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 Model

Django Model A template is a class representing a table or collection in our DB and where each class attribute is a table or collection area. In the app / models.py, models are...

6 minutes read.

Django DRF

Django Rest Framework, which is also referred to as DRF, is a very powerful application to build RESTful APIs in a Django application. DRF uses the Django framework. Similar to...

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.

How to create an app in Django

Create an application in Django Django is famous for its unique and fully managed application structure. For each functionality, an application can be created as a completely independent module. This article will take...

2 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 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 REST Framework

Django REST Framework (DRF)is an open-source, powerful, and flexible toolkit used to build RESTful web APIs. It is built upon the Django framework. DRF increases the development speed. Django and...

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

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.

Best Django courses

In this tutorial, we will see various courses in python Django available on the internet. Django has become popular these days, so courses on it are also increasing day by...

7 minutes read.