Python中tango with django 1.9版本的templates路径问题请教
按照最新版,一步一步做,但是最后发现模板不存在。书里面建立的 templates 位置和官方不太一样,需要配置,但是我打印路径是对的,很奇怪。rango 是 APP 的名字,tango_with_django_project 是项目名字。
├─rango
│ │ admin.py
│ │ apps.py
│ │ models.py
│ │ tests.py
│ │ urls.py
│ │ views.py
│ │ init.py
│ │
│ ├─migrations
│ │ │ init.py
│
│
│
└─tango_with_django_project
│ settings.py
│ urls.py
│ wsgi.py
│ init.py
│
├─templates
│ └─rango
│ index.html
settings 根据文档是这么配置的
TEMPLATE_PATH = os.path.join(BASE_DIR, ‘templates’)
TEMPLATES = [
{
‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,
‘DIRS’: [TEMPLATE_PATH],
‘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’,
],
},
},
]
打印 TEMPLATE_PATH 路径如下:
C:\Users\GARRY\myenv\tango_with_django_project\templates
和创建目录路径是符合的
views.py 里是这么写的:
def index(request):
context_dict = {‘boldmessage’: ‘Tango with Django,hahaha’}
return render(request, ‘rango/index.html’, context=context_dict)
最后报错,说找不到
TemplateDoesNotExist at /
rango/index.html
Request Method: GET
Request URL: http://localhost:8000/
Django Version: 1.11.2
Exception Type: TemplateDoesNotExist
Exception Value: rango/index.html
看下了国外类似问题,与我写的一样,所以最后求救各位。谢谢
https://stackoverflow.com/questions/29987619/templatedoesnotexist-at-rango
Python中tango with django 1.9版本的templates路径问题请教
树图看不清楚,templates 是建立在项目 tango_with_django_project 下的,然后下面是 rango-index.html
在Django 1.9中,TEMPLATES配置已经统一到settings.py的字典结构中。如果你在使用《Tango with Django》教程时遇到模板路径问题,核心是正确配置DIRS选项。
假设你的项目结构如下:
myproject/
├── manage.py
├── myproject/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── templates/
└── rango/ # 你的应用模板目录
在settings.py中需要这样配置:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, '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',
],
},
},
]
关键点:
DIRS列表需要包含你的模板根目录的绝对路径os.path.join(BASE_DIR, 'templates')会生成/path/to/your/project/templates这样的路径APP_DIRS: True允许Django在每个应用的templates/目录中查找模板
这样配置后,你可以在templates/rango/目录下放置模板文件,在视图中使用render(request, 'rango/index.html')就能正确找到模板。
如果还是找不到模板,检查BASE_DIR是否正确指向项目根目录。
总结:确保DIRS路径指向你的模板目录。
问题找到了 ,是配置路径的问题 。谢谢大家。
最后发现可能是版本问题,还是按照官方最新的 1.11 的,把 templates 建立在 APP 目录下。
可以试试用继承 View 类的类来写 view, 这种
from django.views.generic.base import View
class index(View):
def get(self, request):
context_dict = {‘boldmessage’: ‘Tango with Django,hahaha’}
return render(request, ‘rango/index.html’, context=context_dict)

