如果用户未登录,我想阻止用户查看导航栏上的某些链接。
我在模板中使用if语句来执行此操作。当我登录时,它会显示正确的链接集,但是当我退出时却没有。
它应该显示带有登录链接的ul
。我做错了什么?
这是我的代码:
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
{% block head %}
{% endblock %}
</head>
<body>
<style>
ul, li {
margin: 0px 14px;
}
</style>
<nav class = "navbar fixed-top navbar-light bg-light justify-content-between flex-nowrap flex-row">
<div class = " container">
<a class = "navbar-brand float-left" href = "{% url 'Identities:nest'%}">nest</a>
{% if user.is_authenticated %}
<ul class = "nav navbar-nav flex-row float-left ">
<li class = "nav-item "><a class = "nav-link" href = "{% url 'Identities:logout'%}">Sign Out</a></li>
<li class = "nav-item"><a class = "nav-link" href = "{% url 'Identities:view_profile' %}">view Identity </a></li>
<li class = "nav-item"><a class = "nav-link" href = "{% url 'Identities:edit_profile' %}">edit Identity </a></li>
</ul>
{% else %}
<ul class = "nav navbar-nav flex-row float-left ">
<li class = "nav-item "><a class="nav-link" href = "{% url 'Identities:login'%}">Sign In</a></li>
</ul>
{% endif %}
</div>
</nav>
{% block body %}
{% endblock %}
</body>
</html>
答案 0 :(得分:1)
此示例将为匿名用户显示登录,为登录用户显示 logout :
<nav>
<!--your code-->...
<div class="nav navbar-right">
{% if user.is_authenticated %} <!--check if the user is logged in-->
<a href="log-in-url">Log out</a>
{% else %} <!--if not logged in (Anonymous user)-->
<a href="log-in-url">Log in</a>
{% endif %}
</div>
</nav>
答案 1 :(得分:0)
将您的if语句更改为以下内容:
{% if request.user.is_authenticated %}
这应该可以解决你的问题。