Ad

Template Doesn't Exist Using Generic Views

- 1 answer

following the django tutorial I have changed to generic views and now my templates cannot be found anymore.

error: TemplateDoesNotExist at /artdb/test2

it seems that it finds the right directory:

Using engine django:
django.template.loaders.filesystem.Loader: /Users/jonas/Dropbox/prog/web/django/winmalist/templates/artdb/test2 (Source does not exist)

path to templates:

 /Users/jonas/Dropbox/prog/web/django/winmalist/templates/artdb:
  total used in directory 24 available 9223372036852770383
  [email protected] 5 jonas  staff  160 Sep 20 09:59 .
  [email protected] 4 jonas  staff  128 Sep  9 15:50 ..
  [email protected] 1 jonas  staff  215 Sep 19 10:47 index.html
  [email protected] 1 jonas  staff  212 Sep 19 16:02 test1.html
  [email protected] 1 jonas  staff  253 Sep 20 09:59 test2.html

urls.py:

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

app_name='artdb'
urlpatterns = [
    path('artdb',TemplateView.as_view(template_name='index')),
    path('test2',TemplateView.as_view(template_name='artdb/test2')),
#     path('', views.IndexView.as_view(), name='index'),
#     path('contract', views.contract, name='contract'), 
#     path('<int:person_id>/test1/', views.test1, name='test1'),

settings.py:

ROOT_URLCONF = 'winmalist.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(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',
            ],
        },
    },
]
Ad

Answer

You forgot the .html suffix here:

app_name='artdb'

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

The template_name points to a file (with a "relative" filepath), and that includes the extension.

documentation about class-based views normally also contain the .html suffix.

Note that except for some noteworthy edge-cases, one typically subclasses these Views, and thus implement logic around it (like the render context, etc.).

Ad
source: stackoverflow.com
Ad