Home Django TemplateView in Django

TemplateView in Django

A view is a callable that receives a request and responds. Django gives an example of several classes you can use like views, so this can be more than just a function. You may arrange your views and reuse code by utilizing inheritance and mixins. There are some generic views for jobs that we’ll go over later, but you may wish to create your reusable view structure that meets your needs. Django provides a set of base view classes you can use in various applications.

Django TemplateView

All views are descended from the View class, which is responsible for attaching the View to URLs, dispatching HTTP methods, and other standard functionality. The TemplateView extends the primary class to render a template and provide an HTTP redirect.

Incorporate it into your URLconf

Creating generic views directly in your URLconf is the most direct approach to use them. You can give a few attributes into the as_view() function call itself if you’re updating a few characteristics on a class-based view:

from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
path('about/', TemplateView.as_view(template_name="about.html")),
]

Any arguments supplied to as_view() override any class-level attributes. As a result, we set template_name on the TemplateView in this example. On RedirectView, a similar overriding pattern can be utilized for the URL attribute.

Creating subclasses for generic views

The second, more powerful technique of using generic views is to inherit from an existing view and override attributes like the template_name or methods like get_context_data in your subclass to give additional values or methods.

Take, for example, a view that only shows the about.html template. We can subclass TemplateView and override the template name. Django has a generic view to achieving this – TemplateView – as a result, we can subclass it and override the template name:

# code_app/views.py
from django.views.generic import TemplateView

class AboutView(TemplateView):
    template_name = "about.html"

After that, we must include this new View in our URLconf. Because TemplateView is a class rather than a function, we use the as_view() class method to offer a function-like entrance to class-based views:

# urls.py
from django.urls import path
from some_app.views import AboutView

urlpatterns = [
    path('about/', AboutView.as_view()),
]

Support for Other HTTP techniques

Assume someone wants to use the views as an API to access our book library through HTTP. Now and then, the API client would connect and get book data for the books published since the previous visit.

However, if no new books have appeared since then, fetching them from the database, rendering a complete response, and sending them to the client is a waste of CPU time and bandwidth. It might be better to inquire about the most recent book’s publication date with the API. In the URLconf, we map the URL to the book list view:

from django.urls import path
from books.views import BookListView

urlpatterns = [
    path('books/', BookListView.as_view()),
]

Below is the View:

from django.http import HttpResponse
from django.views.generic import ListView
from books.models import Book

class BookListView(ListView):
    model = Book

    def head(self, *args, **kwargs):
        last_book = self.get_queryset().latest('publication_date')
        response = HttpResponse(
            # RFC 1123 date format.
            headers={'Last-Modified': last_book.publication_date.strftime('%a, %d %b %Y %H:%M:%S GMT')},
        )
        return response

In the response, an object list is returned using the codemodel_list.html template if the View is requested via a GET request.
On the off chance that the client sends a HEAD request, the response will have no content, and the Last-Modified header will show when the most recent book was released.

It is two-way traffic for the client to download or not to download the entire object list based on this information.

Deep dive into TemplateView

Django Templates are used to build HTML interfaces rendered by Django views. In addition, Django includes many generic views based on classes to help with everyday tasks. TemplateView is the most basic of them all. It renders a given template using the context parameters contained in the URL.

When you wish to present information on an HTML page, you should use TemplateView. On the other hand, if your page has forms and creates or updates items, TemplateView should not be used. FormView, CreateView, or UpdateView are preferable choices in certain situations.

In the following situations, TemplateView is the best choice:

  • Showing pages that use GET requests but don’t have any forms. ‘About us’ pages are static and don’t require any context. Context variables are simple to use with TemplateView.

A TemplateView is a class-based view that allows developers to design a view for a particular template without reinventing the wheel. Django provides many generic views, the simplest of which is TemplateView. Subclass TemplateView and provide the template_name via the template name variable to construct a view for an example index.html template.

When you develop views that display static HTML pages without context or forms that reply to GET requests, TemplateView is more convenient. TemplateView is a subclass of the View class that renders a Django template and sends it to the client using some repetitious and boilerplate code.

Example of Django View

Let’s look at making a Django view from scratch before moving on to TemplateView. Let’s suppose we’re making a home view. Below is the needed code you must include in your application’s views.py file.

from django.shortcuts import render
from django.views.generic.base import View

class Home(View):
    def get(self, request, *args, **kwargs):
        return render(request, "index.html")

If our project is called myapp, you must first create a templates/myapp folder within myapp and then add an index.html template. The index.html file is located at myapp/templates/myapp/index.html.

So, how does View help us?

It just exposes the get function, which must contain any code executed when a GET request to the associated URL is made. You don’t need to check for a GET request. Instead, just put your code in the get method. In this example, we utilized extra code to render and return the index.html template using a HttpResponse.

Example of a Django TemplateView

This is where TemplateView comes in. Instead of extending View, override the get method and then use a render function to parse the template and return a HttpResponse object. All you need to do is extend the TemplateView. The preceding example has been changed to use TemplateView:from django.views.generic.base import TemplateView

class Home(TemplateView):
  template_name = 'index.html'

After that, place your index.html template in the appropriate folder, and you’re ready to go! You don’t have to override the get function, and use renders or another way to implement it. In TemplateView, it’s already done for you.

If you look at the TemplateView implementation, you’ll notice a get implementation that uses the template in the template name variable and renders it. Because this is a typical pattern, it can be easily isolated and defined in its class, which Django developers may reuse without reinventing the wheel.

The definition of context variables and the template name are better separated in TemplateView. In essence, a TemplateView aids you in avoiding boilerplate code such as:

  • The need for a GET() implementation
  • Creating and returning a HttpResponse() or HttpResponse() subclass object.

The only condition is that you specify in the template is using the template_name variable, as this is the only way for TemplateView to detect the template you wish to render.

Context of a Django Template with a View

Use Template Context if you don’t want your template to be entirely static. Let’s look at how you can use a View class to give your template context. It is the previous example, but this time we’ll pass a primary context object to the template to make it more dynamic.

from django.shortcuts import render
from django.views.generic.base import View

class Home(View):
    def get(self, request, *args, **kwargs):
        context = {'message': 'Hello Django!'}
        return render(request, "index.html", context=context)

Build a context object, name it whatever you want, and provide the render method as the second parameter.

TemplateView with Django Template Context

Now let’s have a look at the previous example using TemplateView:

from django.views.generic.base import TemplateView

class Home(TemplateView):
    template_name = 'index.html'

    def get_context_data(self, *args, **kwargs):
        context = super(Home. self).get_context_data(*args, **kwargs)
        context['message'] = 'Hello World!'
        return context

If you’re using TemplateView, you’ll need to utilize the get_context_data method to give your template any context data variables. You rename the get_context_data function and provide an implementation that receives a context dict object from the parent class (in this case, TemplateView) and adds the message data.

Then, in your index.html template, you may utilize interpolation curly brackets to display your context variable.

<p>{{message}}</p>

Using as_view with TemplateView and URLs

After you’ve defined the sub-class of TemplateView, you’ll need to map it to a URL in your project’s urls.py file. To do so, use TemplateView as a view method, which provides a callable object. The latter is provided as the second parameter to the route method, which correlates URLs with views.

Consider the following scenario:

from django.urls import path
from myapp import views

urlpatterns = [
    # [...]
    path('', views.Home.as_view())
]

Using TemplateView in urls.py

You can use TemplateView directly in your URL for even simpler scenarios. This allows you to render a template more quickly:

from django.views.generic.base import TemplateView
from django.urls import path

urlpatterns = [
    # [...]
    path('', TemplateView.as_view(template_name='index.html'))
]

You can supply the template name as a keyword argument to TemplateView’s view method.

Conclusion

Django includes several generic views based on classes to help with everyday tasks. TemplateView is the most basic of them all. As a result, when presenting information on an HTML page, TemplateView should be utilized. On the contrary, if your page has forms and creates or updates items, TemplateView should not be used.

In some instances, FormView, CreateView, or UpdateView are preferable. However, in the following situations, TemplateView is the best choice:

  • Showing ‘about us’ pages that are static and don’t require many contexts.
  • Context variables are simple to use with TemplateView.
  • Showing pages that use GET requests and don’t contain any forms.

Django’s generic TemplateView view class allows developers to easily create views that display simple templates without reinventing the wheel. Subclass TemplateView and set the template name variable to the name of the template you want to use. You should have this template in your templates folder.

You may also like

Leave a Comment