views.py中的代码:
from django.contrib.auth import authenticate, login as auth_login
def login_view(request):
if request.method=="POST":
login_form = LoginForm(request.POST)
if login_form.is_valid():
data = login_form.cleaned_data
password = data["password"]
username = data["username"]
user = authenticate(username=username, password=password)
if user is not None:
auth_login(request, user)
return redirect(reverse("account:profile", args=(user.id,)))
else:
validation_error = "Enter a valid email or password"
return render(request, "account/login.html", {"form": login_form, "error": validation_error})
else:
login_form = LoginForm()
return render(request, "account/login.html", {"form": login_form, "error": ""})
login.html模板:
{% block login %}
{% if error %}
<p style="color:red;">{{error}}</p>
{% endif %}
<form method="POST">
{% csrf_token %}
{{form}}
<input type="submit" value="Log In">
</form>
{% endblock login %}
url.py:
url(r'login/', user_view.login_view, name='login'),
在转到“ /”时,我被重定向到“ / accounts / login”,将我带到登录页面。输入用户名和密码后,它将带我到用户个人资料页面。
到目前为止,一切都很好。现在,我不再被重定向到“ /”,而是再次被重定向到“ / accounts / login”,并再次显示登录页面。为什么?
答案 0 :(得分:0)
您可以这样做,
return redirect('account:profile', user.pk)
或者您是否要检查用户是否处于活动状态或暂停状态等,
if user is not None:
if user.is_active:
login(request, user) # in your case auth_login as you are importing as auth_login
return redirect('account:profile', user.pk)
注意:
1.确保您的个人资料网址正确,即profile/<int:pk>/
2.(与您的问题无关)-您可以使用Django的内置消息代替验证错误