我无法找到一种方法来使用我已在views.py文件中设置的cookie对应的值
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
我现在必须在我的模板 index.html 中使用与 logged_in cookie-key相对应的值。
{% 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 %}
答案 0 :(得分:0)
最好创建一个变量并将其传递给模板:
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
并在模板中:
{% if your_desired_value %}
{# do magic #}
{% endif %}
您也不需要明确传递user
变量,它始终可以request.user