Django Class Based Views

Posted by Daksh on Sunday, August 7, 2022

Template View

TemplateView is a view that renders a template. It takes a template name and a dictionary of context variables. The context variables are made available in the template context. A class-based view subclasses the django.view.View base class.

from django.views.generic import TemplateView

class MyView(TemplateView):
    template_name = "myapp/index.html"

    def get_context_data(self, **kwargs:Any) -> Dict[str, Any]:
        context = super(MyView, self).get_context_data(**kwargs)
        context['some_data'] = 'This is just some data'
        return context

Inside url.py

from django.urls import path
from .views import MyView
urlpatterns = [
    path('', MyView.as_view(), name='index'),
]

Redirect View

RedirectView is a view that redirects to a given URL. It takes a URL and an optional permanent argument. If permanent is True, the redirect will use a 301 (Moved Permanently) status code. If it’s False, it will use a 302 (Found) status code.

from django.views.generic import RedirectView

class MyView(RedirectView):
    url = 'http://www.example.com/'
    permanent = False

ListView

ListView is a view that displays a list of objects. It takes a queryset and a template name. The context variable passed to the template will be object_list.

from django.views.generic import ListView

class MyView(ListView):
    # do not instantiate this class, just point to it
    model = Model_Name
    queryset = Model_Name.objects.all()
    template_name = "myapp/index.html"
    # if not specified, the context variable is "object_list"
    context_object_name = 'my_list'

    # override get_queryset() to filter the queryset
    def get_queryset(self):
        return Model_Name.objects.filter(name__startswith='Daksh')

DetailView

DetailView is a view that displays a detail page for a particular object. It takes a queryset and a template name. The context variable passed to the template will be object.

from django.views.generic import DetailView

class MyView(DetailView):
    # do not instantiate this class, just point to it
    model = Model_Name
    queryset = Model_Name.objects.all()
    template_name = "myapp/index.html"
    # if not specified, the context variable is "object"
    # it uses the primary key to get the object, this primary key is passed in the url
    # url should have plaveholder for the primary key, like this: <int:pk>
    context_object_name = 'my_object'

    # override get_queryset() to filter the queryset
    def get_queryset(self):
        return Model_Name.objects.filter(name__startswith='Daksh')

FormView

FormView is a view that displays a form, processes it and redirects to a success URL. It takes a form class, a template name and a success URL. The context variable passed to the template will be form.

from django.views.generic import FormView

class MyView(FormView):
    form_class = MyForm
    template_name = "myapp/index.html"
    success_url = '/thanks/'

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        form.save()
        return super(MyView, self).form_valid(form)

CreateView

CreateView is a view that displays a form for creating an object, processes it and redirects to a success URL. It takes a form class, a template name and a success URL. The context variable passed to the template will be form. It validates the form and saves the object.

from django.views.generic import CreateView

class MyView(CreateView):
    model = Model_Name
    # form_class = MyModelForm
    fields = ['name', 'age']
    template_name = "myapp/index.html"
    success_url = '/thanks/'