Django templateview not recognizing my template_name

Question:

Currently I have in settings set my main directory to the templates folder so that I have a project level templates. Within that folder I have a home.html file.

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [BASE_DIR / "templates"],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},

]

This is my views.py file:

from django.views.generic import TemplateView

class HomePageView(TemplateView):
    template_name: "home.html"

Whenever I runserver I receive this error: ImproperlyConfigured at /
TemplateResponseMixin requires either a definition of ‘template_name’ or an implementation of ‘get_template_names()’

I’m following a book to the T (Django for Beginners) and I’m unsure why this error could be happening. Has the syntax for template_name changed? I’ve checked all the documentations and my name seems to be okay. I’ve also tried to input the pathname to the file instead.

Asked By: Koomos

||

Answers:

You have used the view incorrectly. Replace the : with = and it should be fine.

Answered By: William Otieno

You are making an annotation: you should use an equals sign = instead of a colon ::

from django.views.generic import TemplateView


class HomePageView(TemplateView):
    template_name = 'home.html'

Normally templates are also "namespaced" by putting these into a directory with the name of the app, so:

from django.views.generic import TemplateView


class HomePageView(TemplateView):
    template_name = 'app_name/home.html'

and thus put the template in the directory of the app_name/templates/app_name/home.html. This prevents that you later would collide with a template with the same name in a different app.

Answered By: Willem Van Onsem
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.