Andrea
Andrea

Reputation: 163

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.

Upvotes: 4

Views: 8302

Answers (2)

Thank you

from pathlib import Path 
import os

BASE_DIR = Path(__file__).resolve().parent.parent

Upvotes: 1

Alasdair
Alasdair

Reputation: 308879

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__)))

Upvotes: 9

Related Questions