django - 即使在登录后 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”,并再次显示登录页面。为什么?
解决方案
你可以这样做,
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 内置消息代替验证错误
推荐阅读
- css - 防止子元素使用父类
- android - 在 Android Things 上手动配置网络适配器
- python - Python删除for循环中的第一行
- php - Laravel 喜欢不工作的地方。LIKE % % 无法正常工作
- java - 用 Java 下载后在 ftp 服务器上使文件为空/清除
- django - AttributeError:类型对象“_io.StringIO”没有属性“StringIO”
- javascript - Javascript Protractor 从列中获取所有值并将它们相加
- gradle - 等效于 api 在 gradle 中的测试依赖关系?
- reactjs - NumberInput 解析为数字
- c++ - 如何为非常量和常量重载实现一次成员函数?