Access request in django custom template tags

ぃ、小莉子 提交于 2019-11-26 23:48:42
Ignacio Vazquez-Abrams

request is not a variable in that scope. You will have to get it from the context first. Pass takes_context to the decorator and add context to the tag arguments.

Like this:

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

I've tried solution from above (from Ignacio Vazquez-Abrams) and it actually didn't work until I've found out that context processors works only with RequestContext wrapper class.

So in main view method you should add the following line:

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

I've done this way:

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)

There is also a function called resolve_variable, but it's deprecated.

Hope it helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!