我正在尝试为django 3.1.2开发一个博客项目,但是无法链接模板。我尝试使用**'DIRS': [os.path.join(BASE_DIR, 'templates'),]
**对其进行修复,我找不到逻辑上的缺失。该模板确实存在,并且当我查看代码时,查询正在正确执行。我很茫然。
我的设置
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',
],
},
},
]
我的博客urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('', include('posts.urls')),
path('admin/', admin.site.urls),
]
我的帖子urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
我的帖子views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return render(request,'posts/index.html')
答案 0 :(得分:0)
如果您的模板文件夹位于应用程序的目录中 例如:app_name / templates / app_name /.html,那么您无需添加 'DIRS':[os.path.join(BASE_DIR,'templates'),]'。
因此,如果您的应用程序名称是my_posts,请在您的应用程序目录中创建一个名为template的文件夹。然后再次在模板目录中创建一个名为my_posts(与应用程序名称相同)的文件夹,然后在其中创建所有html文件。但是请记住,在进行渲染时,您必须在views.py中执行“ my_posts / index.html”
如果您在主目录/项目目录中有模板文件夹,则只需添加'DIRS':[os.path.join(BASE_DIR,'templates'),]'。