Open In App

TemplateView – Class Based Generic View Django

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Showing ‘about us’ like pages that are static and hardly need any context. Though, it is easy to use context variables with TemplateView.
  • Showing pages that work with GET requests and don’t have forms in them.

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.

  • Enter the following code into views.py file of geeks app.

Python3




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")


  • Create a folder named templates inside the geeks app and then create a file named aboutus.html inside templates folder.
  • Enter the following code into aboutus.html file.

HTML




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


  • Enter the Following code into urls.py of geeksforgeeks project folder.

Python3




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")
]


 
 

  • Run below three commands to see the output.
Python manage.py makemigrations
Python manage.py migrate
Python manage.py runserver
  • Same output can be achieved using TemplateView , replace code of  views.py file of geeks app by given below code.

 

Python3




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 – 



Last Updated : 25 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads