2010-01-29 71 views
62

我的代码:访问请求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 

我参考了这一个 In Django, is it possible to access the current user session from within a custom tag?

+1

嗯......该链接问题的答案似乎是错误的... – 2010-01-29 06:35:42

+0

如果你想访问请求检查这个答案http://stackoverflow.com/a/2567234/1153703 – 2016-07-12 05:02:11

回答

140

request不是该范围内的变量。你必须首先从上下文中获得它。 Pass takes_context to the decorator and add context to the tag arguments

像这样:

@register.inclusion_tag('new/userinfo.html', takes_context=True) 
def address(context): 
    request = context['request'] 
    address = request.session['address'] 
    return {'address':address} 
+0

它似乎我仍然有错误 TemplateSyntaxError at/ 在呈现时捕获到异常:'请求' 原始回溯(最近呼叫最后一次): 文件“C:\ Python25 \ lib \ site-packages \ django \ template \ debug.py”,第71行,在render_node result = node.render(context) 文件“C:\ Python25 \ lib \ site-packages \ django \ template \ __ init__.py”,第936行,在渲染中 dict = func(* args) File “c:\ ... \ myapp_extras.py”,行7,登录 request = context ['request'] 文件“C:\ Python25 \ lib \ site-packages \ django \ template \ context.py”,第44行,在__getitem__中引发KeyError(key) KeyError: “请求” – icn 2010-02-04 06:55:24

+5

我注意到,在这个页面http://docs.djangoproject.com/en/dev/ref/templates/api/ “DJANGO.CORE.CONTEXT_PROCESSORS.REQUEST 如果TEMPLATE_CONTEXT_PROCESSORS包含了这个处理器,每个RequestContext将包含一个变量请求,它是当前的HttpRequest。请注意,此处理器默认情况下未启用;你必须激活它。” 地方我需要配置激活请求处理器 – icn 2010-02-04 06:58:24

+1

为什么这与使用inclusion_tag的情况? – aehlke 2012-04-05 16:19:17

11

我试图解决从上面(从伊格纳西奥巴斯克斯 - 艾布拉姆斯),它实际上没有工作,直到我发现了这方面的处理器仅适用于RequestContext包装类。

所以在主视图的方法,你应该加入下面一行:

from django.template import RequestContext   
return render_to_response('index.html', {'form': form, }, 
           context_instance = RequestContext(request)) 
+0

事实上,context_instance = RequestContext(request)是一个缺失的部分。用它! – 2012-11-01 00:49:00

+3

如果你正在渲染对string/html的响应,你可以不用RequestContext。 '@ register.simple_tag(takes_context = True) ',然后'def my_tag(context,...)... return render_to_response('index.html',{'form':form,},context_instance = context) '。 – osa 2013-12-16 05:29:29

7

我所做的这样:

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功能,但它的弃用。

希望它有帮助!