Reputation: 1681
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
Reputation: 476547
There are two problems here:
template_name
; andreturn
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