Class-based views

Class-based views

from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views import View

from .forms import MyForm

class MyFormView(View):
    form_class = MyForm
    initial = {'key': 'value'}
    template_name = 'form_template.html'

    def get(self, request, *args, **kwargs):
        form = self.form_class(initial=self.initial)
        return render(request, self.template_name, {'form': form})

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            # <process form cleaned data>
            return HttpResponseRedirect('/success/')

        return render(request, self.template_name, {'form': form})
  • Allow you to structure your views and reuse code by harnessing inheritance and mixins.
  • Provide an alternative way to implement views as Python objects instead of functions.
  • Do not replace function-based views, but have certain differences and advantages when compared to function-based views.
  • If you have tried function based generic views in the past and found them lacking, you should not think of class-based generic views as a class-based equivalent, but rather as a fresh approach to solving the original problems that generic views were meant to solve.

Related concepts

Class-based views — Structure map

Clickable & Draggable!

Class-based views — Related pages: