我用 Django 编写了一个应用程序。我想为它写一个 index.html。但我不能让它运行。我尝试并检查了设置和代码,但它也不起作用。我会粘贴代码。希望有人能找到窍门。
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',
'django.core.context_processors.static',
],
},
},
]
我写了一个名为博客的应用程序。我把 index.html 放在 ,blog/templates/blog/
views.py
def index(request):
posts = Post.objects.filter(published=True)
return render(request,'blog/index.html',{'posts':posts})
urls.py:
urlpatterns = [
url(r'^$', views.index, name='index')
]
我找不到任何问题,但它就是行不通。似乎找不到模板,但配置路径是正确的。或者我错过了一些我不知道的事情?
最佳答案
将“博客”添加到 settings.py
中的 INSTALLED_APPS
元组中
此外,以下是适合我的设置。希望这些也能帮到您。
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_BASE_PATH = os.path.dirname(__file__)
PROJECT_DIR_NAME = os.path.split(PROJECT_BASE_PATH)[1]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(PROJECT_BASE_PATH, 'templates').replace('\\', '/')],
'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_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
关于python - django 中的模板问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30658176/