首页 > 解决方案 > 即使在登录后 Django 也会重定向到登录页面(我使用了自定义登录登录表单)

问题描述

view.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 %}

网址.py:

url(r'login/', user_view.login_view, name='login'),

在转到“/”时,我被重定向到“/accounts/login”,这会将我带到登录页面。输入用户名和密码后,它会将我带到用户个人资料页面。

到目前为止,一切都很好。现在,我没有被重定向到“/”,而是再次被重定向到“/accounts/login”,并再次显示登录页面。为什么?

标签: django

解决方案


你可以这样做, 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 内置消息代替验证错误


推荐阅读