如何在 Django 中以编程方式验证用户身份?
如何在 Django 中以编程方式登录用户?我有用户的用户名和密码。有没有一种方法可以让我登录他?
How can I log-in the user programmatically in Django? I have the username and password of the User. Is there a method that let's me log him in?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除了“以编程方式”之外,没有其他方法。当然,这是 记录的。
There is no other way than "programmatically". Of course, this is documented.
以编程方式登录用户时请务必小心,您可能会收到错误“
用户没有属性“后端”
。如果以前没有发生过这种情况,您也必须设置后端。 使用此项目和一些示例代码:Alsways be careful when programmatically logging users in, you might get the error ´
user has no attribute "backend"
. You have to set the backend too if that has no happened previously. Project that uses this and some sample code:接受的答案肯定有效,但是,我更喜欢使用内置身份验证表单的 Django,例如 django.contrib.auth.forms.AuthenticationForm
下面是一个片段,显示了重要部分
这种方法的主要区别是
AuthenticationForm.clean
方法为您调用authentication
函数并为您检查User.is_active
。The accepted answer definitely works but, I prefer to use the Django built in auth forms, like
django.contrib.auth.forms.AuthenticationForm
Here is a snippet that shows the important part
The major difference in this approach is that
AuthenticationForm.clean
method callsauthentication
function for you and checksUser.is_active
for you as well.