Подтвердить что ты не робот

Запрос доступа в пользовательских тегах шаблона django

Мой код в файле 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

Я ссылался на этот В Django можно ли получить доступ к текущему сеансу пользователя из пользовательского тега?.

4b9b3361

Ответ 2

Я пробовал решение сверху (от Ignacio Vazquez-Abrams), и он фактически не работал, пока я не узнал, что контекстные процессоры работают только с RequestContext классом-оболочкой.

Итак, в основном методе просмотра вы должны добавить следующую строку:

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

Ответ 3

Я сделал так:

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, но она устарела.

Надеюсь, что это поможет!