How To Write Class-Based Views With DRY Code Using Inheritance In Django?

Django has many rich amounts of features that it provides at its best. One of these is Class-Based Views. It provides an alternative way to implement views as Python objects instead of functions. They don’t replace function-based views, but have some advantages and differences compared to function-based views. Class-based views are simpler and efficient to manage than function-based views. The function-based view with multiple lines of code can be converted into a Class-based view with only a few lines of code. We’ll be going through a basic example of how to use it for the “DRY” (Don’t Repeat Yourself) code. In the end, you’ll save a lot of redundant code in your views file.

Requirements: Must be having a simple Django project setup in local.

Prerequisites: We will be using Template View in this example:

1. Set

This file is for all views and functions.

from django.views.generic import TemplateView

class Base(TemplateView):
#define functions
#define context function
#return context variable

class IndexView(Base): #Inheriting Base View
#define functions for index template
#define context function for index template
#return context variable of index template

2. Set

This file is for urls to be defined.

from .views import *
urlpatterns = [path('index/', IndexView.as_view(), name="index"),]

3. Set index.html

This file is for the html code.

<!doctype html>
<title> {{base_context_variable }} </title>
<h2> {{index_variables }} </h2>

In this tutorial, we learned how to write Class-based views with DRY code using inheritance in Django. This tutorial touched on the basics and focused very little on styling and extensibility.

Visit Gist for reference: Click here

Mobio Solutions is a leading Python development company. With the ability to build custom applications Python becomes one of the most popular programming languages among various industries. At Mobio Solutions, our machine learning and data analysis & mining services deliver high-quality applications with enhanced features to increase the ROI of the business.