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

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

问题描述

我在 myapp_extras.py 中的代码:

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}

在settings.py"中:

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:Python25libsite-packagesdjango	emplatedebug.py", line 71, in render_node
    result = node.render(context)
  File "C:Python25libsite-packagesdjango	emplate\__init__.py", line 915, in render
    dict = func(*args)
  File "C:p4projectsmyproject..myprojectinvoice	emplatetagsmyapp_extras.py", line 9, in address
    address = request.session['address']
NameError: global name 'request' is not defined

我参考了这个在Django,是否可以从自定义标记中访问当前用户会话?.

推荐答案

request 不是该范围内的变量.您必须首先从上下文中获取它.takes_context 传递给装饰器并将 context 添加到标签参数.

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.

像这样:

@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天全站免登陆