在django自定义模板标签中访问请求
我在myapp_extras.py中的代码:
from django import template register = template.Library() @register.inclusion_tag('new/userinfo.html') def address(): address = request.session['address'] return {'address':address}
在'settings.py'中:
TEMPLATE_CONTEXT_PROCESSORS =( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", 'django.core.context_processors.request' )
但我得到一个错误:
TemplateSyntaxError at /items/ Caught an exception while rendering: global name 'request' is not defined Original Traceback (most recent call last): File "C:\Python25\lib\site-packages\django\template\debug.py", line 71, in render_node result = node.render(context) File "C:\Python25\lib\site-packages\django\template\__init__.py", line 915, in render dict = func(*args) File "C:\p4\projects\myproject\..\myproject\invoice\templatetags\myapp_extras.py", line 9, in address address = request.session['address'] NameError: global name 'request' is not defined
我引用这个在Django中,是否可以从自定义标记中访问当前用户会话? 。
request
不是该范围内的variables。 你将不得不从上下文中得到它。 将takes_context
传递给装饰器并向标记参数添加context
。
喜欢这个:
@register.inclusion_tag('new/userinfo.html', takes_context=True) def address(context): request = context['request'] address = request.session['address'] return {'address':address}
我已经尝试了从上面(来自Ignacio Vazquez-Abrams)的解决scheme,直到我发现上下文处理器只与RequestContext
包装类一起工作,它实际上不工作。
所以在主视图方法中,你应该添加以下行:
from django.template import RequestContext return render_to_response('index.html', {'form': form, }, context_instance = RequestContext(request))
我这样做了:
from django import template register = template.Library() def do_test_request(parser,token): try: tag_name = token.split_contents() # Not really useful except ValueError: raise template.TemplateSyntaxError("%r error" % token.contents.split()[0]) return RequestTestNode() class RequestTestNode(template.Node): def __init__(self,): self.request = template.Variable('request') def render(self, context): rqst = self.request.resolve(context) return "The URL is: %s" % rqst.get_full_path() register.tag('test_request', do_test_request)
还有一个名为resolve_variable
的函数,但不推荐使用。
希望能帮助到你!