我的模板标签中需要request.path。但问题是,我的django版本是1.5.1而我没有TEMPLATE_CONTEXT_PROCESSORS
,所以没有django.core.context_processors.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})
active_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 ''
答案 0 :(得分:1)
请在上下文字典中传递请求对象。
def home(request):
photos = Photo.objects.all()
return render(request,"index.html", {'photos':photos,'request':request})
答案 1 :(得分:0)
如果希望请求对象始终在模板中可用,则可以添加到默认模板上下文处理器。请参阅答案:
Where is template context processor in Django 1.5?
基本上,将它放在您的settings.py中:
import django.conf.global_settings as DEFAULT_SETTINGS
TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
'django.core.context_processors.request',
)