django template view

django template view

Django comes with a reusable class based views and TemplateView is one of them. For rendering a simple pages like static text or with a little context we use it.

When to use TemplateView?

  • when a rendering the static pages or pages with a little context
  • Example use cases:
    • About us page
    • Terms and conditions

UML diagram for TemplateView

django template view

From above UML diagram we can see the see it's parent classes TemplateResponseMixin, ContextMixin and View and their respective methods. As the class TemplateView inheriting these classes it will aquire all properties and methods from these classes. So, we can override/overload the required methods based on our requirement.

Methods execution order 1. dispatch() 2. get() 3. get_context_data() 4. render_to_response()

Usage of TemplateView in django

Let's see few examples to implement the about us page.

about_us.html

<html>
    <body>
        <h1> About Us</h1>
        <p>It's about me.</p>
    </body>
</html>

views.py

from django.views.generic import TemplateView

class AboutUs(TemplateView):
    template_view = "about_us.html"

It's that simple to create about us page by using the generic TemplateView in django.

sending extra context to TemplateView

We can send extra context to the template by overriding the method get_context_data

about_us.html

<html>
    <body>
        <h1> About Us</h1>
        <p>sample text</p>
        <p>{{content}}</p>
    </body>
</html>

views.py

from django.views.generic import TemplateView

class AboutUs(TemplateView):
    template_view = "about_us.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["content"] = "Hello Batta"
        return context

Like above code, we can pass the extra context to the template. It's that simple to use the django TemplateView.

Ref: https://docs.djangoproject.com/en/3.2/ref/class-based-views/base/#templateview