Search code examples
pythondjangodjango-templatespython-3.8django-3.1

How to set Django template path properly?


In most recent django documentation "Overriding from the project’s templates directory" https://docs.djangoproject.com/en/3.1/howto/overriding-templates/ it shows that you can use the following path for templates:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        ...
    },
]

I tried using [BASE_DIR / 'templates'] but I keep getting the following error:
TypeError: unsupported operand type(s) for /: 'str' and 'str'

It all works fine when I change the code to: [BASE_DIR , 'templates'] or [os.path.join(BASE_DIR , 'templates')], no problem in such case.
Can someone explain what am I missing with the [BASE_DIR / 'templates'] line? Thank you.

I'm using Python 3.8 and Django 3.1.


Solution

  • In order to use BASE_DIR / 'templates', you need BASE_DIR to be a Path().

    from pathlib import Path
    
    BASE_DIR = Path(__file__).resolve().parent.parent
    

    I suspect that your settings.py was created with an earlier version of Django, and therefore BASE_DIR is a string, e.g.

    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))