我正在使用Django身份验证系统,并希望在用户登录网站后创建注销按钮。但是user.is_authenticated无法正常工作,甚至在登录页面上也显示了注销按钮。有人可以帮我了解我在想什么吗? 下面是我的views.py和模板代码-
查看:
def user_login(request):
form=LoginForm()
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
print("came here")
if user.is_active:
login(request,user)
return redirect('valid')
else:
return HttpResponse('username or password not correct')
else:
return render(request, 'restui/login.html',{'form':form})
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>REST API Framework</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-dark bg-primary">
<a href="#" class="navbar-brand" style="font-family: 'Lato', sans-serif;">REST API Testing Framework</a>
{% if request.user.is_authenticated %}
<button class="btn btn-light" type="submit">Logout</button>
{% endif %}
</nav>
<br>
<br>
<br>
<nav class="navbar fixed-bottom">
<div class="container">
<div class="navbar-header">
<a href="#" class="navbar-brand"></a>
</div>
<ul class="nav navbar-nav">
<li>
<a href="#"><img src="infosys-logo.jpg" style="max-height:100px; max-width:90%; right:1px; "></a>
</li>
</ul>
</div>
</nav>
{% block body_block %}
<div class="container">
<form method="post">
<div class="form-group">
{{ form.username.label }} {{ form.username }}
</div>
<div class="form-group">
{{ form.password.label }} {{ form.password }}
</div>
<br>
{% csrf_token %}
<button type="submit" class="btn btn-primary">Submit</button>
<small id="emailHelp" class="form-text text-muted">Login issues? Please contact solutions team to get access.</small>
</form>
</div>
{% endblock %}
</body>
</html>
答案 0 :(得分:1)
好吧,即使您在登录页面上,您的用户仍然可以通过身份验证。您可以检查用户是否已通过身份验证,而只是重定向到另一个页面,以使登录的用户看不到登录页面。
def user_login(request):
form=LoginForm()
if request.user.is_authenticated:
print("Already logged in")
return redirect('valid')
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
print("came here")
if user.is_active:
login(request,user)
return redirect('valid')
else:
return HttpResponse('username or password not correct')
else:
return render(request, 'restui/login.html',{'form':form})
答案 1 :(得分:0)
尝试此 {% if user.is_authenticated %}
这是我的代码
{% if user.is_authenticated %}
<li><a href="{% url 'logout' %}"><i class="fa fa-sign-out pull-right"></i> Log Out</a></li>
{% else %} <a href="{% url 'login' %}" class="fa fa-sign-out pull-right"> LogIn </a>
{% endif %}