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)