Welcome to our in-depth tutorial on Django's TemplateView! This lesson is designed for beginners and intermediate learners, focusing on practical, real-world examples. Let's dive in!
TemplateView is a class-based view in Django that allows you to render a template and return an HttpResponse object. It's a simple yet powerful tool for creating dynamic web pages.
TemplateView is useful when you want to render a template with dynamic data. Unlike FunctionViews, TemplateViews are class-based, making them more flexible and reusable.
base.html template for your application. This will serve as a foundation for your other templates.<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
<!-- Your head content here -->
</head>
<body>
<!-- Your body content here -->
</body>
</html>example.html.<!-- example.html -->
{% extends 'base.html' %}
{% block content %}
<h1>Hello, World!</h1>
{% endblock %}from django.views.generic import TemplateView
class ExampleView(TemplateView):
template_name = 'example.html'from django.urls import path
from . import views
urlpatterns = [
path('example/', views.ExampleView.as_view(), name='example'),
]template_name: The name of the template to be rendered.extra_context: Additional context data to be passed to the template.Suppose you want to create a view that displays a list of books with their authors.
<!-- book_list.html -->
{% extends 'base.html' %}
{% block content %}
<ul>
{% for book in books %}
<li>{{ book.title }} by {{ book.author }}</li>
{% endfor %}
</ul>
{% endblock %}from django.http import Http404
from django.views.generic import ListView
from .models import Book
class BookListView(ListView):
model = Book
template_name = 'book_list.html'urlpatterns = [
path('books/', views.BookListView.as_view(), name='book_list'),
]What does TemplateView do in Django?
We hope this comprehensive guide has helped you understand Django's TemplateView. Stay tuned for more in-depth tutorials on Django! π― Happy coding! β