Home > Mobile >  Django throws TemplateDoesNotExist for a template located it in the 'my_app/templates/my_app�
Django throws TemplateDoesNotExist for a template located it in the 'my_app/templates/my_app�

Time:09-22

I am studying Django and got stuck right at the first project. I've got TemplateDoesNotExist exception when accessing index page of my application. I saw a lot of same looking questions here, but answers seem to be referring to slightly different cases or older Django versions.

Template-loader postmortem shows that Django looked for the index page (index.html) in the 'movies/templates' directory, while file is placed inside 'movies/templates/movies' as it is suggested by manuals.

Project info

Project structure

'movies' is added to the INSTALLED_APPS list in the settings.py

And movies/views.py refers to the index.html in following way:

def all_films(request):
    return render(request, 'index.html', {'movies': my_movies, 'director': settings.DIRECTOR})

What worked

Adding 'os.path.join(BASE_DIR, 'movies', 'templates', 'movies'),' to the TEMPLATES['DIRS'] values in the settings.py makes it work, but after reading manuals and answers to same questions I assume it shouldn't be required.

Also, if I change movies/views.py so that it refers to 'movies/index.html' instead of 'index.html' everything works. But is it a good practice to use app name in links like this? I mean, it could be hard to maintain in future etc.

Question

Basically, question is what am I doing/getting wrong. Could you please suggest, what else should I check to make it work in default state without manual editing of TEMPLATES' DIRS property?

P.S. I am using Django 3.2.7, OS is Ubuntu.

CodePudding user response:

Check if 'APP_DIRS': True in settings.py>TEMPLATES

CodePudding user response:

This should work!

settings.py

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',
            ],
        },
    },
]

views.py

def all_films(request):
    return render(request, 'movies/index.html', {'movies': my_movies, 'director': settings.DIRECTOR})
  • Related