简体   繁体   English

Django'DIRS':settings.py模板中的[]导致“ TemplateDoesNotExist”错误

[英]Django 'DIRS': [] in settings.py TEMPLATES causes “TemplateDoesNotExist” Error

I'm using django version 2.1.2 with python 3.6. 我正在使用Django 3.6的Django版本2.1.2。

I created two django projects (test01 & test02) by CMD. 我用CMD创建了两个django项目(test01和test02)。 Both of the projects are under the same folder. 这两个项目都在同一文件夹下。 Test01 executes normally, while test02 raises TemplateDoesNotExist error. Test01正常执行,而test02引发TemplateDoesNotExist错误。 在此处输入图片说明

I've found a solution for the latter that is hard coding the address of templates in settings.py: 我发现了后者的解决方案,该解决方案是在settings.py中硬编码模板的地址:

'DIRS': [r'C:\\django\\test02\\accounts\\templates'] 'DIRS':[r'C:\\ django \\ test02 \\ accounts \\ templates']

However, another project can run normally even leaving this list as blank []. 但是,即使将该列表留为空白[],另一个项目也可以正常运行。

The structures of both projects are the same: 这两个项目的结构相同: 在此处输入图片说明

Can anyone give a suggestion that can fix the problem in test02 without hard coding the address of templates in test02? 谁能提出一个建议,在不对test02中的模板地址进行硬编码的情况下解决test02中的问题?

You may notice a built-in Django variable named BASE_DIR , it represents your root project, so you don't need to hard code the absolute path. 您可能会注意到一个名为BASE_DIR的内置Django变量,它代表您的根项目,因此您无需对绝对路径进行硬编码。

Add this in settings 在设置中添加

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # codes...
            ],
        },
    },
]

Register all your apps, and Django will look for any files inside a folder named templates as you mentioned in os.path.join(BASE_DIR, 'templates') 注册所有应用程序,然后Django将在os.path.join(BASE_DIR, 'templates')提到的名为templates的文件夹中查找任何文件。

Let create a folder called "test01App" in template and create base.html on it. 让我们在模板中创建一个名为“ test01App”的文件夹,并在其上创建base.html。 then you can call 'test01App/base.html' in response. 那么您可以致电“ test01App / base.html”作为回应。
BACKEND is default of django and you have to create folder "templates". BACKEND是django的默认设置,您必须创建文件夹“ templates”。 you can custom where store template in other place in DIRS. 您可以自定义DIRS中其他位置的模板存储位置。

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, './cuong')],
    'APP_DIRS': True,
    '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',
        ],
    },
},

] ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM