darkdefender27 darkdefender27 - 6 months ago 25
Python Question

Django: Accessing cookie value set in views.py in html template?

I am unable to figure out a way to use the value corresponding to a cookie that I already set in my views.py file

if user.is_active:
login(request, user)
login_dict = {
'user': user,
}
max_age = 60 * 60
response = render(request, 'index.html', login_dict)
response.set_cookie('logged_in', 'request.POST['email']', max_age)
return response


I have to now use the value corresponding to logged_in cookie-key inside my template index.html.

{% if request.COOKIES (<--*This is where I am facing the problem*)%}
<li>
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> {{ request.COOKIES.logged_in }} <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Settings</a></li>
<li><a href="#">Preferences</a></li>
<li class="divider"></li>
<li><a href="/logout/">LogOut</a></li>
</ul>
</li>
{% else %}
<li>
<a href="/login/">Login</a>
</li>
<li>
<a href="/register/">Register</a>
</li>
{% endif %}

Answer

it's better to create a variable and pass it into the template:

if user.is_active:
    login(request, user)
    login_dict = {
        'user': user,
        'your_desired_value': desired_value, # your new variable
    }
    max_age = 60 * 60
    response = render(request, 'index.html', login_dict)
    response.set_cookie('logged_in', request.POST['email'], max_age)
    return response

and in the template:

{% if your_desired_value %}
     {# do magic #}
{% endif %}

also you don't need to pass user variable explicitly, it's always accessible as request.user

Comments