How to solve “TemplateDoesNotExist” error in Django

Sept. 30, 2020, 6:56 a.m.

This error means Django was unable to find a particular template in your Django app , you might be asking yourself which template exactly is not being found ? Now for us to Know the exact template, we will have to go to our settings.py file and find this line


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

If you look at the documentation it describes the TEMPLATES variable as a list containing the settings for all template engines to be used with Django. Each item of the list is a dictionary containing the options for an individual engine.

By default Django is able to load templates from the templates subdirectory inside each installed application , the templates that cannot be found automatically are the ones which are not in our installed application , in short the templates that are in the same level as manage.py file are the ones that cannot be found automatically , read more on this here

So how do we find those templates outside of installed applications, we have to set the DIRS to point to the correct path where our template which are outside our installed appllication will be found . We will do this by setting the TEMPLATES variable like so


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

As you can see, 'DIRS' above is set to point to the path where these templates will be found by using this line os.path.join(BASE_DIR, 'templates') . Now our templates which are outside the installed apps will be found easy by Django.

Resources

Keep Learning