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.
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.
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.
- 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.
- Enter the Following code into urls.py of geeksforgeeks project folder.
- Run below three commands to see the output.
Python manage.py makemigrations Python manage.py migrate Python manage.py runserver
- Same ouput can be achieved using TemplateView , replace code of views.py file of geeks app by given below code.
Let’s check what is there on http://localhost:8000/
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.