[英]Django is_authenticated and @login_required both not working
I tried to make some pages only visible when logged in. 我试图使某些页面仅在登录时可见。
I tried it with: 我尝试了:
def backend(request):
if request.user.is_authenticated:
return render(request, 'web/backend-index.html')
else:
return redirect(reverse('web:login'))
and also with: 以及:
@login_required
def backend(request):
return render(request, 'web/backend-index.html')
The first code does not let me log in. 第一个代码不允许我登录。
The second code does not let me log in but the url changes too: http://127.0.0.1:8000/login/?next=/backend/ 第二个代码不允许我登录,但URL也会更改: http : //127.0.0.1 : 8000/login/?next=/backend/
If I just render the view without checking if logged in, the login is working fine and I´ll be passed to the backend page. 如果仅渲染视图而不检查是否已登录,则登录工作正常,并且将被传递到后端页面。
The whole code is on github: https://github.com/psmaster1/BrainSystems/tree/master/smarthome/web 整个代码在github上: https : //github.com/psmaster1/BrainSystems/tree/master/smarthome/web
I don't get any error messages. 我没有收到任何错误消息。 It's just redirecting to the login page... 它只是重定向到登录页面...
Your login form is incorrect - that's why you never actually authenticate. 您的登录表单不正确-这就是为什么您从未真正进行身份验证的原因。 It was sending POST request to incorrect endpoint and it was not rendering actual form. 它正在向不正确的端点发送POST请求,并且未呈现实际表单。 This is how you can render fields manually 这是您可以手动呈现字段的方式
Change it to this: 更改为此:
<section class="login-form">
<div class="login-fields">
<h3>Login</h3>
<form method="POST">
{% csrf_token %}
<div class="form-group">
{{ login_form.username }}
<label for="{{ login_form.username.id_for_label }}" class="control-label">Username</label><i class="bar"></i>
{{ login_form.username.errors }}
</div>
<div class="form-group">
{{ login_form.password }}
<label for="{{ login_form.password.id_for_label }}" class="control-label">Passwort</label><i class="bar"></i>
{{ login_form.password.errors }}
</div>
<div class="button-container">
<input type="submit" class="button" value="Login" />
</div>
</form>
<p>Noch nicht Registriert?</p>
<a href="{% url 'web:register' %}">Registrieren</a>
</div>
</section>
Already fixed it! 已经解决了! The Problem was the action attribute in the form tag. 问题是表单标记中的action属性。 It causes the troubles. 这会引起麻烦。 Just removed it from the form tag and make a redirect in the login() method. 只需将其从form标记中删除,然后在login()方法中进行重定向即可。 Thanks guys! 多谢你们! :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.