相关模块:django.contrib.auth
使用:
1. 创建用户:
User
类默认的属性有:
usename
password
email
first_name
last_name
try:
User.objects.get(username=username)
except User.DoesNotExist:
user = User.objects.create_user(username,email,
password)
if user is not None:
user.save()
2. 登录:
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
...
else:
# Return an 'invalid login' error message.
...
如果用户名和密码正确,则获得 user
对应于model的用户对象。
3. 退出登录:
auth.logout(request)
4. 密码相关:
user.set_password(raw_password)
user.check_password(raw_password)
5. 权限管理:
Models中的Permisson模块提供了对于每个权限的抽象。创建权限:
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get(app_label='school', model='Discussion')
permission = Permission.objects.create(codename='can_publish',
name='Can Publish Discussions',
content_type=content_type)
User对象可以直接管理拥有的权限:
myuser.user_permissions.set([permission_list])
myuser.user_permissions.add(permission, permission, ...)
myuser.user_permissions.remove(permission, permission, ...)
myuser.user_permissions.clear()
检验用户是否拥有某个权限:
has_perm(perm, obj=None)
has_perms(perm_list, obj=None)
同时,Models中的Group模块提供了对用户角色的抽象,每一种角色对应一个group,也就拥有特定的一组权限。
用户管理权限组的方法:
myuser.groups.set([group_list])
myuser.groups.add(group, group, ...)
myuser.groups.remove(group, group, ...)
myuser.groups.clear()
参考资料:
Using the Django authentication system
django.contrib.auth
https://www.jianshu.com/p/01126437e8a4
网友评论