我是django的新手,在django运行服务器时,我正面临着一个问题,我已经复制并粘贴了我的代码,请告诉我我的代码出了什么问题
'DIRS': [templates],
NameError: name 'templates' is not defined
在settings.py文件中,我已将模板放在[]括号中
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [templates],
'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',
],
},
},
]
这是我的views.py
from django.http import HttpResponse
from django.shortcuts import render
def index(response):
return render(request,'index.html')
这是urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'),
path('about', views.about, name='about'),
]
答案 0 :(得分:1)
您需要在此处更改 DIRS
'DIRS': [os.path.join(BASE_DIR, 'templates')],
在这里,Django期望它具有模板路径,但是您提供了templates
变量,该变量没有任何路径。
答案 1 :(得分:0)
您必须将行更改为此
'DIRS': [os.path.join(BASE_DIR, 'templates')],
在设置文件的开头,您可以看到BASE_DIR
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
将DIRS更改为
'DIRS': [os.path.join(BASE_DIR, 'templates')],
将帮助应用找到模板文件夹。 每个应用程序中只有一个个人建议即可存储特定应用程序的templates / appname文件夹。它将帮助您拥有更强大的Django应用。
例如您有民意测验应用程序,在民意测验应用程序中将是这样
pollsApp / templates / pollsApp / index.html等
答案 2 :(得分:0)
虽然其他人已经对如何解决它给出了正确的答案,但是我想指出一点,您得到tm
是因为您尚未定义名称NameError
。
当您正在使用的变量未在程序中的任何位置定义时,将引发templates
(如果您在当前作用域之外定义变量,则将得到NameError
)。
如果将名称模板定义为模板文件夹绝对路径的字符串,则可以使用。尽管如此,仍然不要在Django应用程序中使用绝对路径,因为它在部署时会变得令人头疼。
答案 3 :(得分:0)
模板应该是字符串。所以['templates']而不是[templates]