Django’s Generic Views: TemplateView

Next in my series on Django’s generic class-based views is the simple TemplateView, a view whose responsibility lies solely in rendering a template.

As a reminder, the site Classy Class-Based Views is an invaluable resource for understanding Django’s class-based views.

Posts in this series


There’s no additional code required for a TemplateView—just a template. We’ll cover the following attributes, if you want to jump straight to each section:

The Simple TemplateView

A very simple view, the TemplateView has just one required property:

from django.views.generic import TemplateView


class HomeView(TemplateView):
    template_name = "home.html"

The template specified by template_name is rendered by the default template renderer specified in the project’s settings.

My template needs additional context variables.

You can use extra_context for that:

class HomeView(TemplateView):
    template_name = "home.html"
    extra_context = {"section": "blog"}

But the extra data isn’t static, though.

For anything more complex, you can override get_context_data:

class HomeView(TemplateView):
    template_name = "home.html"
    extra_context = {"section": "blog"}

    def get_context_data(self, *args, **kwargs):
        context = {
            "post_count": Post.objects.count(),
        }
        return context

For this one template, I want to use Jinja2 instead of Django’s template language.

Sure! Specify that with template_engine:

class HomeView(TemplateView):
    template_name = "home.html"
    template_engine = "jinja2"