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'
)
>>> 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
:
if
user.is_active:
print
(
"User is valid, active and authenticated"
)
else
:
print
(
"The password is valid, but the account has been disabled!"
)
else
:
print
(
"The username and password were incorrect."
)
|