django - 读取模板标签中的请求变量

标签 django session request django-context

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

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

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

template 标签中的代码如下(代码自第一篇文章以来已扩展):

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.core.context_processors.request 添加到 settings.py 中的 TEMPLATE_CONTEXT_PROCESSORS 中,则代码有效。

关于django - 读取模板标签中的请求变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18261854/

相关文章:

python - 更改 dotcloud 上的依赖项代码。 Django

django - Django 模板中的搜索字段

java - 如何中断 Hibernate session ?

Django:如何触发新模型的 ContentTypes 创建?

python - 如何在虚拟机中启动服务器 Django (Vagrant)

java - 在 Eclipse 中关闭 Java 程序时保存 session

javascript - html中如何获取session?

python - Django Web 应用程序与 BeautifulSoup ,请求

node.js - 使用 request 和 Cheerio 模块延迟请求

php - 创建 PHP API : Checking from which server the API Request comes from