[英]Django after login failed page is not redirecting to next
如果用户成功登录,则它会重定向到下一页,但如果用户无法登录,那么我想更改模板并希望重定向到下一页,但它不起作用。
视图.py
def login(request, template_path='login.html'):
"""
"""
# We'll only allow staff to view this page after login.
if request.user.is_authenticated:
return redirect('home')
if request.method == 'POST':
if request.META['HTTP_REFERER'].split('/')[-1] == 'bs5':
template_path = 'theme/bs5_theme.html'
response = LoginView.as_view(
template_name=template_path,
redirect_field_name='next',
form_class=EmailAuthenticationForm,
)(request)
if request.is_ajax():
if request.user.is_authenticated:
return HttpResponse(
json.dumps(dict(success=True, next=request.POST.get("next"))),
content_type="application/json"
)
return HttpResponse(json.dumps(False), content_type="application/json")
else:
return response
else:
form = auth_forms.AuthenticationForm()
model = dict(login_form=form)
return render(request, template_path, model)
登录.html
{% if form.non_field_errors %}
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
Login failed. Email and password case-sensitive.
</div>
{% endif %}
<form id="formLogin" action="{% url 'login' %}" method="post" role="form">
<input type="hidden" name="csrfmiddlewaretoken">
<input type="hidden" name="next" value="/bs5" />
<label for="id_username" class="form-label">Email address</label>
<input type="username" class="form-control" id="id_username" name="username" value="{{ form.username.value }}">
<label for="id_password" class="form-label">Password</label>
<input type="password" class="form-control" id="id_password" name="password">
<button class="btn btn-primary btn-lg" type="submit">Log In</button>
</form>
我也试过
return HttpResponseRedirect('/bs5')
但是它没有显示登录错误。
任何帮助,将不胜感激。
如果您想重定向无法登录到其他页面的用户,您可以采用的方法之一是:
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect
def login(request, template_path='login.html'):
if request.user.is_authenticated:
redirect('home')
user = authenticate(request, username= request.POST.get('username'), password=request.POST.get('password'))
if user is not None:
next_url = request.POST.get('next') # get your next url
messages.error(request, _('Invalid credentials')) # display login error on the next page
return redirect(next_url)
else:
login(request, user)
# redirect to the successful url that you wish to
有关在模板中显示消息的更多信息,您可以查阅django 的文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.