Open In App

TemplateView – Class Based Generic View Django

Django provides several class based generic views to accomplish common tasks. The simplest among them is TemplateView. It Renders a given template, with the context containing parameters captured in the URL.

TemplateView should be used when you want to present some information on an HTML page. TemplateView shouldn’t be used when your page has forms and does creation or update of objects. In such cases, FormView, CreateView, or UpdateView is a better option.



TemplateView is most suitable in the following cases:

Explanation :



Illustration of How to use TemplateView using an Example. Consider a project named geeksforgeeks having an app named geeks.

Refer to the following articles to check how to create a project and an app in Django. 
  

How to Create a Basic Project using MVT in Django ? 
  

How to Create an App in Django ?

Let’s write a view using base class view View and then modify it to use TemplateView. TemplateView would help us avoid several lines of code.




from django.views.generic.base import View
from django.shortcuts import render
 
class AboutUs(View):
  def get(self, request, *args, **kwargs):
        return render(request, "aboutus.html")




<!DOCTYPE html>
<html>
<head>
<title>AboutUs</title>
</head>
<body>
<h2>Welcome To GFG</h2>
</body>
</html>




from django.contrib import admin
from django.urls import path
from geeks.views import AboutUs
 
urlpatterns = [
    path('admin/', admin.site.urls),
      path('',AboutUs.as_view(),name="aboutus")
]

 
 

Python manage.py makemigrations
Python manage.py migrate
Python manage.py runserver

 




from django.views.generic.base import TemplateView
 
class AboutUs(TemplateView):
    template_name = 'aboutus.html'

Let’s check what is there on http://localhost:8000/

Output – 


Article Tags :