我正在将Django 2.1.2和python 3.6一起使用。
我用CMD创建了两个django项目(test01和test02)。 这两个项目都在同一文件夹下。 Test01正常执行,而test02引发TemplateDoesNotExist错误。
我为后者找到了一种解决方案,该解决方案是在settings.py中硬编码模板的地址:
'DIRS':[r'C:\ django \ test02 \ accounts \ templates']
但是,即使将该列表保留为空白[],另一个项目也可以正常运行。
任何人都可以提出一个可以解决test02问题的建议,而无需在test02中硬编码模板地址吗?
答案 0 :(得分:1)
您可能会注意到一个名为BASE_DIR
的内置Django变量,它代表您的根项目,因此您无需对绝对路径进行硬编码。
在设置中添加它
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# codes...
],
},
},
]
注册所有应用,然后Django将在templates
os.path.join(BASE_DIR, 'templates')
的文件夹中的所有文件。
答案 1 :(得分:0)
让我们在模板中创建一个名为“ test01App”的文件夹,并在其上创建base.html。
那么您可以调用“ test01App / base.html”作为响应。
BACKEND是django的默认设置,您必须创建文件夹“ templates”。
您可以自定义将模板存储在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',
],
},
},
]