Elcid_91
Elcid_91

Reputation: 1681

Django rendering template in view class

In an attempt to further understand the Django framework, I am writing a small test case. The app name is "login" and I have the following defined:

urls.py:

from django.urls import path

from .views import Index

urlpatterns = [
    path('', Index.as_view(), name='index')
]

views.py:

from django.shortcuts import render
from django.views.generic import TemplateView


class Index(TemplateView):
    template_name = "/login/index.html"

    def get(self, request):
        render(request, self.template_name, None)

Running into a problem loading the page:

TemplateDoesNotExist at /login/

index.html is located in the login app folder:

/login/templates/login/index.html

What concepts am I missing here?

Upvotes: 2

Views: 3835

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476547

There are two problems here:

  1. you should not add a leading slash to the template_name; and
  2. you forgot to specify a return statement:
class Index(TemplateView):
    template_name = "login/index.html"

    def get(self, request):
        return render(request, self.template_name, None)

That being said, a TemplateView [Django-doc] actually already implements the render logic itself. It is used to omit the boilerplate logic.

If you want to add context data in a TemplateView, you need to override the get_context_data(…) method [Django-doc]:

class Index(TemplateView):
    template_name = 'login/index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['some_variable'] = 42
        return context

We here added an extra variable some_variable to the context that we render with the template.

Upvotes: 4

Related Questions