Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 532
Andrea Avatar asked Mar 02 '23 02:03

Andrea


2 Answers

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__)))
like image 199
Alasdair Avatar answered Mar 05 '23 16:03

Alasdair


Thank you

from pathlib import Path 
import os

BASE_DIR = Path(__file__).resolve().parent.parent
like image 31
Manatsapan Chomchansin Avatar answered Mar 05 '23 16:03

Manatsapan Chomchansin