设为首页 加入收藏

TOP

Django用户认证系统(一)User对象(二)
2019-02-12 16:07:57 】 浏览:92
Tags:Django 用户 认证 系统 User 对象
t_password(raw_password)
设置密码。

check_password(raw_password)
验证密码。

get_group_permissions(obj=None)
返回用户组权限的集合。

get_all_permissions(obj=None)
返回用户所有的权限集合。

has_perm(perm, obj=None)
用户是否具有某个权限。perm的格式是 "<app label>.<permission codename>". 

has_perms(perm_list, obj=None)
用户是否具有权限列表中的每个权限。

创建用户

由于User对象的密码不是明文存储的,所以创建User对象时与通常的Model create不同,需用内置的create_user()方法。

1
2
3
4
5
6
7
8
>>>  from  django.contrib.auth.models  import  User
>>> user  =  User.objects.create_user( 'john' 'lennon@thebeatles.com' 'johnpassword' )
 
# At this point, user is a User object that has already been saved
# to the database. You can continue to change its attributes
# if you want to change other fields.
>>> user.last_name  =  'Lennon'
>>> user.save()

当然也可以在admin界面中添加用户。

创建superusers

1
$ python manage.py createsuperuser  - - username = joe  - - email = joe@example.com

修改密码

使用内置的set_password()方法。

1
2
3
4
>>>  from  django.contrib.auth.models  import  User
>>> u  =  User.objects.get(username = 'john' )
>>> u.set_password( 'new password' )
>>> u.save()

验证用户

authenticate()

验证给出的username和password是否是一个有效用户。如果有效,则返回一个User对象,无效则返回None。

1
2
3
4
5
6
7
8
9
10
11
from  django.contrib.auth  import  authenticate
user  =  authenticate(username = 'john' , password = 'secret' )
if  user  is  not  None :
     # the password verified for the user
     if  user.is_active:
         print ( "User is valid, active and authenticated" )
     else :
         print ( "The password is valid, but the account has been disabled!" )
else :
     # the authentication system was unable to verify the username and password
     print ( "The username and password were incorrect." )

  

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇asyncio之Coroutines,Tasks and F.. 下一篇TensorFlow数据集(二)——数据..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目