Python 2.7和Django 1.10我的模板存在,但我做错了!
TemplateDoesNotExist at /basicview/2/
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>TEST</title>
</head>
<body>
This is template_two view!
</body>
</html>
Request Method: GET
Request URL: http://127.0.0.1:8000/basicview/2/
Django Version: 1.10.1
Exception Type: TemplateDoesNotExist
Exception Value:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>TEST</title>
</head>
<body>
This is template_two view!
</body>
</html>
Exception Location: /home/i/djangoenv/local/lib/python2.7/site-packages/Django-1.10.1-py2.7.egg/django/template/loader.py in get_template, line 25
Python Executable: /home/i/djangoenv/bin/python
Python Version: 2.7.11
Python Path:
['/home/i/djangoenv/bin/firstapp',
'/home/i/djangoenv/lib/python2.7',
'/home/i/djangoenv/lib/python2.7/plat-i386-linux-gnu',
'/home/i/djangoenv/lib/python2.7/lib-tk',
'/home/i/djangoenv/lib/python2.7/lib-old',
'/home/i/djangoenv/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-i386-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/home/i/djangoenv/local/lib/python2.7/site-packages',
'/home/i/djangoenv/local/lib/python2.7/site-packages/Django-1.10.1-py2.7.egg',
'/home/i/djangoenv/lib/python2.7/site-packages',
'/home/i/djangoenv/lib/python2.7/site-packages/Django-1.10.1-py2.7.egg']
Server time: Пт, 23 Сен 2016 15:43:30 +0000
settings.py (os.path.join(BASE_DIR),'templates'或/ home / mainapp / templates)无法正常工作..
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',
],
},
},
article/views.py 我的def看起来像:
def template_two(request):
view = "template_two"
t = get_template('myview.html')
html = t.render(Context({'name': view}))
return render(request, html, {})
我的档案:
mainapp/mainapp/settings.py
mainapp/mainapp/article/views.py
mainapp/templates/myview.html
3 回答
问题是您手动渲染模板并同时使用
render
快捷方式 . 您的get_template
正在运行,但是当您调用render(request, html, {})
时,Django将html
视为文件名,并查找名为<!DOCTYPE html>\n<html>...
的模板文件 .您应该手动渲染模板:
或者,使用
render
快捷方式更简单 .您还应该将
DIRS
设置更改回使用os.path.join(BASE_DIR, 'templates')
. 使用字符串'templates'
不起作用 .我建议你把你的temlates放在你的应用程序中 .
您的文件将在此处:
请确保将
mainapp
添加到您的INSTALLED_APPS
中,如下所示:在你的settings.py中你有
'DIRS': ['templates'],
模板的路径是
mainapp/templetes/myview.html
你有拼写错误
templetes != templates
. 将模板重命名为templates
.