简体   繁体   English

Django:访问html模板中views.py中设置的cookie值?

[英]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 我无法找出一种方法来使用与我已经在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

I have to now use the value corresponding to logged_in cookie-key inside my template index.html . 我现在必须在模板index.html中使用与logging_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 %}

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 而且您不需要显式传递user变量,它始终可以作为request.user访问

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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