【问题标题】:Read request variable in template tag读取模板标签中的请求变量
【发布时间】:2013-08-18 04:24:23
【问题描述】:

我正在将一个 Django 项目变成一个多语言站点。为此,我正在尝试采用countries-for-django (github) 包。

在其中一个模板标签中,代码试图读取会话变量 django_country(取自 here),但 Django 1.5 在从上下文中读取 request 变量时出错。

Exception Type: AttributeError 
Exception Value: 'NoneType' object has no attribute 'session'

模板标签中的代码如下(从第一次发帖开始,代码已经扩展):

class GetCurrentCountryNode(Node):
    def __init__(self, variable):
        self.variable = variable

    def get_current_country(self, context):
        from django.template import Context
        return context.get('request').session.get('django_country')

    def render(self, context):
        context[self.variable] = self.get_current_country(context)
        return ''

...

@register.tag("get_current_country")
def do_get_current_country(parser, token):
    args = token.contents.split()
    if len(args) != 3 or args[1] != 'as':
        raise TemplateSyntaxError("'get_current_country' requires 'as variable' (got %r)" % args)
    return GetCurrentCountryNode(args[2])

当我打印context 变量时,打印输出不包含任何request 变量。但是,我可以通过Django Toolbar 看到该变量是存在的。

Django 1.5 读取上下文变量的方式有变化吗? 我在文档中找不到任何内容。

为完整性添加了 Views.py 和模板。

views.py

...
class StartView(FormView):
    form_class = StartForm
    template_name = 'home.html'

    def form_valid(self, form):
        self.request.session['address'] = form.cleaned_data['address']
        return HttpResponseRedirect(reverse_lazy('new'))
...

home.html

{% load countries %}    
{% get_current_country as country %}
{% get_available_countries as COUNTRIES %}

<head>
... 

【问题讨论】:

    标签: django session request django-context


    【解决方案1】:

    如果将django.core.context_processors.request 添加到settings.py 中的TEMPLATE_CONTEXT_PROCESSORS,则代码有效。

    【讨论】:

      猜你喜欢
      • 2011-10-29
      • 2011-05-13
      • 1970-01-01
      • 2011-09-24
      • 2017-05-17
      • 2018-10-13
      • 1970-01-01
      • 2012-01-15
      • 2011-10-06
      相关资源
      最近更新 更多