简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM