📅  最后修改于: 2023-12-03 14:40:46.596000             🧑  作者: Mango
Django TemplateView is a class-based view that renders a template. It is a powerful tool for creating dynamic web pages in Django.
To use the TemplateView, you need to create a view that extends the class and specify the template name to use. Here is an example:
from django.views.generic import TemplateView
class HomePageView(TemplateView):
template_name = 'home.html'
Here, we have created a HomePageView
that will render the home.html
template.
TemplateView also allows you to pass context data to the template. To do this, you can override the get_context_data
method of the class. Here is an example:
class AboutPageView(TemplateView):
template_name = 'about.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['about_text'] = 'This is the about page'
return context
Here, we have passed the about_text
variable to the about.html
template.
TemplateView supports the GET and HEAD HTTP methods. When a request is made with the HEAD method, it only returns the HTTP headers without the response body.
Django TemplateView is a powerful tool for creating dynamic web pages in Django. It allows you to easily render templates and pass context data to them.