Template View – 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:



class index(TemplateView):
	template_name = 'blogpost/index.html'


Create a folder named templates inside the blogpost app, create another folder with the same name as the app i.e, blogpost inside the templates folder and then create a file named index.html inside templates folder.

Lets write the above view using base class view View.



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




from django.urls import path
from . import views

urlpatterns = [
    path('index', views.index.as_view(), name='index'),
]

Latest Blog