User
默认属性
1 | username |
Diagram
所属方法
1 | is_anonymous(): |
创建管理员用户
1 | python manage.py createsuperuser --username=joe --email=joe@example.com |
修改User Ojbect的密码
方式一:代码1
2
3u = User.objects.get(username='john')
u.set_password('new password')
u.save()
方式二:后台管理
登陆自带的后台管理系统修改用户密码
注意:用户修改密码后,根据自己系统的设计,可能需要更新session,否则可能会遇到Session invalidation on password change
验证用户
默认验证用户方法
django.contrib.auth.backends.ModelBackend
1 | from django.contrib.auth import authenticate |
如果验证不通过,系统抛出PermissionDenied异常
自定义验证
Permissions and Authorization
用户权限类型
Access to view the “add” form and add an object is limited to users with the “add” permission for that type of object.
Access to view the change list, view the “change” form and change an object is limited to users with the “change” permission for that type of object.
Access to delete an object is limited to users with the “delete” permission for that type of object.
Permissions can be set not only per type of object, but also per specific object instance.
By using the has_add_permission(), has_change_permission() and has_delete_permission() methods provided by the ModelAdmin class, it is possible to customize permissions for different object instances of the same type.
User Fields
User objects have two many-to-many fields: groups and user_permissions.
访问这两个属性字段的方法如下:
1 | myuser.groups.set([group_list]) |
默认权限列表
当在setting.py的INSTALLED_APPS添加django.contrib.auth时,执行命令**python manager.py migrate后,系统将为每个Model默认生成3种权限:add,change and delete。
注:python manager.py migrate,创建Model权限列表时,会发出 post_migrate 信号。
Groups
django.contrib.auth.models.Group models are a generic way of categorizing users so you can apply permissions, or some other label, to those users.
A user can belong to any number of groups.
用户的Group权限
A user in a group automatically has the permissions granted to that group. For example, if the group Site editors has the permission can_edit_home_page, any user in that group will have that permission.
简单来说,隶属用户组的用户,自然拥有该用户组所拥有的权限。
Model
自定义权限
To create custom permissions for a given model object, use the permissions model Meta attribute.
示例代码1 Meta
在Task自带的权限外,添加额外的权限属性
1 | class Task(models.Model): |
检查用户权限代码
1 | # codename 查看数据库auth_permission表 |
示例代码2 program
创建一个permission权限属性对象,然后使用 user/group 对象添加这个权限属性对象。
create the can_publish permission for a BlogPost model in myapp:
1 | from myapp.models import BlogPost |
The permission can then be assigned to a User via its user_permissions attribute or to a Group via its permissions attribute.