4

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.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
Andrea
  • 153
  • 1
  • 11
  • 1
    Using `os.path.join()` would be fine, but you shouldn't use `[BASE_DIR , 'templates']` - that is adding two directories to `DIRS` - the base dir itself and `'templates'` (which might work some of the time as a relative directory) – Alasdair Sep 11 '20 at 10:31

2 Answers2

8

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__)))
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • My setting was created with django 3.0, I later upgraded django to 3.1, but the setting is still there. And indeed it says: ```BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))```, So that could be the right answer. – Andrea Sep 11 '20 at 10:25
  • All right, I tried and changed settings from ```BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))``` to ```BASE_DIR = Path(__file__).resolve().parent.parent``` and its working fine now. Thank you @Alasdair – Andrea Sep 11 '20 at 10:28
1

Thank you

from pathlib import Path 
import os

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