django自定义模板标签中的访问请求

2024-05-07

我在 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}

在“设置.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 中,是否可以从自定义标签内访问当前用户会话? https://stackoverflow.com/questions/335231/in-django-is-it-possible-to-access-the-current-user-session-from-within-a-custom.


request不是该范围内的变量。您必须首先从上下文中获取它。Pass takes_context到装饰器并添加context到标签参数 http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags.

像这样:

@register.inclusion_tag('new/userinfo.html', takes_context=True)
def address(context):
    request = context['request']
    address = request.session['address']
    return {'address':address}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

django自定义模板标签中的访问请求 的相关文章

随机推荐