如何在django 1.5中获取request.path?
我需要模板标记中的request.path。但问题是,我的django版本是1.5.1,我没有如何在django 1.5中获取request.path?,django,django-views,django-templates,Django,Django Views,Django Templates,我需要模板标记中的request.path。但问题是,我的django版本是1.5.1,我没有模板\u上下文\u处理器,因此没有django.core.CONTEXT\u处理器.request。现在,它给了我一个错误: Exception Type: AttributeError Exception Value:'str' object has no attribute 'path' Exception Location:C:\Users\Nanyoo\web\pics\album\templa
模板\u上下文\u处理器
,因此没有django.core.CONTEXT\u处理器.request
。现在,它给了我一个错误:
Exception Type: AttributeError
Exception Value:'str' object has no attribute 'path'
Exception Location:C:\Users\Nanyoo\web\pics\album\templatetags\active_tags.py in active, line 8
是否有其他方法可以获得模板中所需的路径
views.py:
def home(request):
photos = Photo.objects.all()
return render(request,"index.html", {'photos':photos})
活动_tags.py:
from django import template
register = template.Library()
@register.simple_tag
def active(request, pattern):
import re
if re.search(pattern, request.path):
return 'active'
return ''
请在上下文字典中传递请求对象
def home(request):
photos = Photo.objects.all()
return render(request,"index.html", {'photos':photos,'request':request})
如果希望请求对象在模板中始终可用,可以添加到默认模板上下文处理器。请看下面的答案: 基本上,将其放入您的settings.py中:
import django.conf.global_settings as DEFAULT_SETTINGS
TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
'django.core.context_processors.request',
)
请在dict
{'photos':photos,'request':request}
中传递请求对象,然后重试。完美!请将您的评论作为答案发布,以便我可以接受。