[Answered ]-Why am I receiving KeyError: 'django' when running python manage.py runserver

1👍

So I assume you aren’t doing custom template stuff, so here’s most likely the fix.

Go into your settings.py and make sure your TEMPLATES look like this:

  • Take specific Note on the BACKEND value
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',
            ],
        },
    },
]

I changed the BACKEND Value to: template.backends.django.DjangoTemplates and I got the same error (removed the first django.)

Traceback (most recent call last):
  File "C:\Users\{me}\Envs\tmpdjango\lib\site-packages\django\template\utils.py", line 71, in __getitem__
    self.run(**options)
    return self._engines[alias]
KeyError: 'django'

and it’s due to:

# django.templates.util. ~26
def templates(self):
    if self._templates is None:
        self._templates = settings.TEMPLATES

    # stuff chopped out


    for tpl in self._templates:
        try:
            # ********** This Line \/ *******************
            default_name = tpl["BACKEND"].rsplit(".", 2)[-2]

            # 'django.template.backends.django.DjangoTemplates'.rsplit(".", 2)[-2]
            # out: 'django'

        except Exception:
            pass # (actually an error here)

    ## futher down
    tpl = {
        "NAME": default_name,
        "DIRS": [],
        "APP_DIRS": False,
        "OPTIONS": {},
        **tpl,
    }

    templates[tpl["NAME"]] = tpl

    # more Stuff

and where the error is happening: alias seems to always be django (not sure why)

# django.templates.util. ~69
def __getitem__(self, alias):

    print('alias',alias)
    # alias == 'django'

    try:
        return self._engines[alias]
    except KeyError:
        try:
            params = self.templates[alias]
            # print(self.templates)
        except KeyError:
            raise InvalidTemplateEngineError(
                "Could not find config for '{}' "
                "in settings.TEMPLATES".format(alias)
            )

Leave a comment