Incorrect Django path to templates folder in settings.py

生来就可爱ヽ(ⅴ<●) 提交于 2021-01-28 08:04:45

问题


I am newly learning Django and was following the Learn Django 1.11 Tutorial.

Here is my current project tree:

├── manage.py
├── muypicky
│   ├── __init__.py
│   ├── old_settings.py
│   ├── settings
│   │   ├── base.py      # Contains the settings (like shown in the tutorial)
│   │   ├── __init__.py
│   ├── urls.py
│   └── wsgi.py
├── requirements.txt
├── restaurants
└── templates           # Templates Folder
└── index.html

I am trying to add the path to the tempelates folder in the settings folder. But the error shown

django.template.loaders.filesystem.Loader: .../muypicky/templates/index.html (Source does not exist)

Current setting.py file

TEMPLATES = [{
  'DIRS': [os.path.join(BASE_DIR, 'templates')], 
  },]

Looking at the error, the file path is wrong because it goes into /muypicky/tempelates which is incorrect. So how do I get to root folder and then into tempelates folder with the given file tree in setting.py (base.py).

Any further queries, just ask and many thanks in anticipation.


回答1:


Solution:

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

and

TEMPLATES = [{'DIRS': [
    os.path.join(BASE_DIR, 'templates')
],},]

Addition of os.path.dirname() was wrapped to go back one folder




回答2:


settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/uploads/'
TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [MEDIA_ROOT + '/'],#other app templates
    'APP_DIRS': True,#heremention yourapp/templates
    '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',
            'django.template.context_processors.media'
        ],
    },
},
]

also can you look at document djano template




回答3:


I faced similar problem and was able to rectify with this:

TEMPLATES = [{
  ....

  'DIRS': [os.path.join(BASE_DIR, '/templates')],

  ....

Dev Environment: django 2.2, python 3.6

so i think you need to add / before the 'templates' string...

I also think this changes with django versions as i'm currently working on another project that didn't require the trailing / before the 'templates' string on django 2.1, python 3.6. So i think this is worth trying out good luck



来源:https://stackoverflow.com/questions/45964127/incorrect-django-path-to-templates-folder-in-settings-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!