Classbased Views (CBV)
In Django, class-based views (CBVs) are a way to organize the code for handling HTTP requests in a reusable manner. Class-based views provide a way to reuse common functionality across multiple views, and make it easier to add or change functionality without duplicating code.
One type of class-based view in Django is the class-based template view. This type of view allows you to render a template in response to an HTTP request. The class-based template view provides a number of advantages over using function-based views, such as better code organization, easier inheritance and customization, and more flexibility in handling HTTP requests.
To create a class-based template view in Django, you can subclass the django.views.generic.base.TemplateView
class and define the template that should be rendered in response to a request. For example, here is a simple class-based template view that renders a template called my_template.html
:
You can then include this view in your urls.py
file like any other view:
When a request is made to /my-view/
, Django will create an instance of MyView
and call its get
method. The get
method will then render the my_template.html
template and return it as an HTTP response.
You can also override other methods in the TemplateView
class to customize the behavior of your view. For example, you can override the get_context_data
method to add additional context variables to your template, or the dispatch
method to add additional functionality before or after the view is executed.
Last updated