访问请求在django自定义模板标签 [英] Access request in django custom template tags

查看:121
本文介绍了访问请求在django自定义模板标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码在myapp_extras.py中:

 从django导入模板

register = template。图书馆()

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

in'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'

但我收到错误:

 code> / items / 

中的TemplateSyntaxError在呈现时捕获异常:全局名称'request'未定义

原始追溯(最近的最后一次调用):
文件C:\Python25\lib\site- packages\django\tem print \\ d
result = node.render(context)
文件C:\Python25\lib\site-packages\django\template \__init __。py,第915行,在render
dict = func(* args)
文件C:\p4\projects\myproject\..\myproject\invoice \templatetags\myapp_extras.py,第9行,地址
address = request.session ['address']
NameError:全局名称'request'未定义

我引用了这个
可以访问当前用户会话

请求不是此范围中的变量。你必须首先从上下文得到它。 通过 took_context 到装饰器,并将上下文添加到标签参数



像这样: / p>

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

My code in 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}

in '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'
)

but I got an error:

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

I referenced this one In Django, is it possible to access the current user session from within a custom tag?.

解决方案

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}

这篇关于访问请求在django自定义模板标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆