Django认证系统user对象实现过程解析
User对象
User对象是认证系统的核心。它们通常表示与你的站点进行交互的用户,并用于启用限制访问、注册用户信息和关联内容给创建者等。在Django的认证框架中只存在一种类型的用户,因此诸如'superusers'或管理员'staff'用户只是具有特殊属性集的user对象,而不是不同类型的user对象。
创建users
创建users最直接的方法是使用create_user()辅助函数:
>>>fromdjango.contrib.auth.modelsimportUser >>>user=User.objects.create_user('john','lennon@thebeatles.com','johnpassword')
fromdjango.contrib.auth.modelsimportUser defcreate_user(request): #auth_user #user=User.objects.create_user('john','lennon@thebeatles.com','johnpassword') #superuserpythonmanage.pycreatesuperuser--username=joe--email=joe@example.com u=User.objects.get(username='john') u.set_password('newpassword') u.save() returnHttpResponse("success-----%s"%u)
创建成功后见数据库auth_user表
创建superusers
使用createsuperuser命令创建superusers:
$pythonmanage.pycreatesuperuser--username=joe--email=joe@example.com
或者
$pythonmanage.pycreatesuperuser
接下来依次输入用户密码即可
成功后见auth_user表
修改密码
>>>fromdjango.contrib.auth.modelsimportUser >>>u=User.objects.get(username='john') >>>u.set_password('newpassword') >>>u.save()
成功后见auth_user表,密码已经改变
authenticate(**credentials)[source]
认证一个给定用户名和密码,请使用authenticate()。它以关键字参数形式接收凭证,对于默认的配置它是username和password,如果密码对于给定的用户名有效它将返回一个User对象。如果密码无效,authenticate()返回None。例子:
fromdjango.contrib.authimportauthenticate user=authenticate(username='john',password='secret') ifuserisnotNone: #thepasswordverifiedfortheuser ifuser.is_active: print() else: print() else: #theauthenticationsystemwasunabletoverifytheusernameandpassword print()
defauth(request): user=authenticate(username='john',password='newpassword')#john #user=authenticate(username='john',password='johnpassword')#None print(user) ifuserisnotNone: #thepasswordverifiedfortheuser ifuser.is_active: print("验证成功,已激活") else: print("验证成功,未激活") else: #theauthenticationsystemwasunabletoverifytheusernameandpassword print("没有此用户") returnHttpResponse(user)
john
验证成功,已激活
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。