如何让 Django 使用当前应用程序的模板文件夹?



现在我有一个包含三个应用程序的Django项目。在我的上一个应用程序中,views.py加载的index.html是另一个应用的templates文件夹中的index.html。请注意,这是它实际加载的方式,但不是我打算加载的方式。没有使用模板中定义相应views.py的index.html。我想知道的是如何定义我的设置,以便使用当前应用程序目录的templates文件夹。这是我的设置.py关于模板:

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',
],
},
},  
]

这是对index.html 的调用

def indexView(request):
form = FriendForm()
friends = Friend.objects.all()
return render(request, "index1.html", {"form": form, "friends": friends})

一个好的做法是,从应用程序的urls.py内部添加:

app_name = 'your_app_name' # Now, you can call this app from the {% url tag %}

你的模板结构应该包含应用程序目录,当你想渲染到不同的模板时,你可以使用:

return render(request, 'myApp1/index.html')
return render(request, 'myApp2/index.html')

但请记住,在您的主模板文件夹中,您需要添加2个目录,

templates/myApp1/index.html, 

templates/myApp2/index.html

最后,您是否将app_name添加到应用程序URL中?然后尝试第一个,或者完整的路径。

{% url 'myApp1:post_friend' %} or full path {% url 'myApp1/index.html' %}

最新更新