Eu Chi
Eu Chi

Reputation: 563

I can't access request in my Django template

Hello Awesome People!

A simple question. I have this view:

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

In my template, I want to access COOKIES, with request

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

I tried displaying {{request.COOKIES}}, nothing shown however the key exists. It seems that request isn't available in the template.

split is a custom tag filter

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

Why I can't access the request?, and also none of my global variables available in my project/context_processors.py are accessible

Upvotes: 0

Views: 2816

Answers (1)

Alasdair
Alasdair

Reputation: 308909

Don't use render_to_response, it's been obsolete since render was introduced in Django 1.3. The render_to_response function was deprecated in Django 2.0 and will finally be removed in Django 3.0.

In this case, change the view to use render as follows:

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

Assuming you have the request context processor enabled in TEMPLATES (it is enabled in the default generated settings file), you will then be able to access request in the template.

Upvotes: 3

Related Questions