django模板中的request.path
Posted
技术标签:
【中文标题】django模板中的request.path【英文标题】:request.path in django template 【发布时间】:2013-03-04 09:41:24 【问题描述】:我尝试这样的事情:
% if request.path == 'contact' %
<p>You are in Contact</p>
% endif %
% if request.path == 'shop' %
<p>You are in Shop</p>
% endif %
为什么不起作用?
【问题讨论】:
您的 TEMPLATE_CONTEXT_PROCESSORS 设置中有什么内容? @Brandon 我的 settings.py 中没有这个配置文件。我使用 django 1.4.5。我想我有默认设置。 尝试输出 request.path
。
【参考方案1】:
试试这个:
% if 'contact' in request.path %
【讨论】:
【参考方案2】:1.8 之前 settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
'other.required.processors.names',
'django.core.context_processors.request',
)
views.py(使用 className.as_view)
from django.template import *
class className(TemplateView):
template_name = "name.html"
views.py(正常使用)
from django.shortcuts import render_to_response
def name(request):
return render_to_response('name.html',context_instance=RequestContext(request))
【讨论】:
【参考方案3】:默认情况下,Django 的模板处理器是
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages"
)
(见documentation)
您需要django.core.context_processors.request
才能在模板中使用request
,因此请将其添加到settings.py 中的列表中。如果那里没有该变量,请设置它。
【讨论】:
从 Django 1.10+ 使用 'django.template.context_processors.request'【参考方案4】:试试:
% if request.path == '/contact/' %
<p>You are in Contact</p>
% elif request.path == '/shop/' %
<p>You are in Shop</p>
% endif %
【讨论】:
request.path 为您提供了整个路径,因此如果路径看起来像这样,它将是 /something/someting/contact/。就是这样。 没错。您必须检查整个路径,我只是根据所提供的内容来举例说明 :) 尝试检查% if 'contact/' in reuqest.path %
。所以你不需要检查完整的路径。以上是关于django模板中的request.path的主要内容,如果未能解决你的问题,请参考以下文章