我无法在Django模板中访问请求

时间:2018-08-09 15:08:23

标签: python django django-templates django-views

您好!

一个简单的问题。我有这种看法:

def hello(request):
     users_list = User.objects.all()
     context = {"users_list":users_list}
     return render_to_response('index/users-list.html',context=context)

在我的模板中,我想使用request

访问COOKIES。
 {% for u in users_list %}
 {% if u.id in request.COOKIES.room|split %}
       remove user
 {% endif %}
 {% endfor %}

我尝试显示{{request.COOKIES}},但是没有显示任何键。似乎该请求在模板中不可用。

  

split是自定义标签过滤器

@register.filter    
def split(string_,sep=","):
    return string_.split(sep)

为什么我无法访问请求?,而且project/context_processors.py中所有可用的全局变量也无法访问

1 个答案:

答案 0 :(得分:3)

不要使用render_to_response,自render在Django 1.3中引入以来,它已经过时了。 render_to_response函数在Django 2.0中已弃用,最终将be removed in Django 3.0

在这种情况下,按如下所示将视图更改为使用render

 return render(request, 'index/users-list.html', context=context)

假设您在request中启用了TEMPLATES context processor(在默认生成的设置文件中启用了此功能),那么您将能够在模板。