Django用户认证系统(三)组与权限
Django的权限系统很简单,它可以赋予users或groups中的users以权限。
Django admin后台就使用了该权限系统,不过也可以用到你自己的代码中。
User对象具有两个ManyToManyField字段,groups和user_permissions
groups = models.ManyToManyField(Group, verbose_name=_('groups'),
blank=True, help_text=_('The groups this user belongs to. A user will '
'get all permissions granted to each of '
'their groups.'),
related_name="user_set", related_query_name="user")
user_permissions = models.ManyToManyField(Permission,
verbose_name=_('user permissions'), blank=True,
help_text=_('Specific permissions for this user.'),
related_name="user_set", related_query_name="user")
可以像其它的django Model一样来访问他们:
myuser.groups = [group_list]
myuser.groups.add(group, group, ...)
myuser.groups.remove(group, group, ...)
myuser.groups.clear()
myuser.user_permissions = [permission_list]
myuser.user_permissions.add(permission, permission, ...)
myuser.user_permissions.remove(permission, permission, ...)
myuser.user_permissions.clear()
权限Permissions
权限是作为一个Model存在的,建立一个权限就是创建一个Permission Model的实例。
@python_2_unicode_compatible
class Permission(models.Model):
"""
The permissions system provides a way to assign permissions to specific
users and groups of users. The permission system is used by the Django admin site, but may also be
useful in your own code. The Django admin site uses permissions as follows: - The "add" permission limits the user's ability to view the "add" form
and add an object.
- The "change" permission limits a user's ability to view the change
list, view the "change" form and change an object.
- The "delete" permission limits the ability to delete an object. Permissions are set globally per type of object, not per specific object
instance. It is possible to say "Mary may change news stories," but it's
not currently possible to say "Mary may change news stories, but only the
ones she created herself" or "Mary may only change news stories that have a
certain status or publication date." Three basic permissions -- add, change and delete -- are automatically
created for each Django model.
"""
name = models.CharField(_('name'), max_length=255)
content_type = models.ForeignKey(ContentType)
codename = models.CharField(_('codename'), max_length=100)
objects = PermissionManager() class Meta:
verbose_name = _('permission')
verbose_name_plural = _('permissions')
unique_together = (('content_type', 'codename'),)
ordering = ('content_type__app_label', 'content_type__model',
'codename') def __str__(self):
return "%s | %s | %s" % (
six.text_type(self.content_type.app_label),
six.text_type(self.content_type),
six.text_type(self.name)) def natural_key(self):
return (self.codename,) + self.content_type.natural_key()
natural_key.dependencies = ['contenttypes.contenttype']
字段fields
name:必需。50个字符或更少,例如,’Can Vote‘
content_type:必需,一个对于django_content_type数据库table的引用,table中含有每个应用中的Model的记录。
codename:必需,100个字符或更少,例如,'can_vote'。
如果要为某个Model创建权限:
from django.db import models class Vote(models.Model):
... class Meta:
permissions = (("can_vote", "Can Vote"),)
如果这个Model在应用foo中,则权限表示为'foo.can_vote',检查某个用户是否具有权限myuser.has_perm('foo.can_vote')
默认权限default permissions
如果已经在 INSTALLED_APPS配置了django.contrib.auth,它会保证为installed applications中的每个Django Model创建3个缺省权限:add, change 和 delete。
这些权限会在你第一次运行 manage.py migrate(1.7之前为syncdb) 时创建。当时所有的models都会建立权限。在这之后创建的新models会在再次运行 manage.py migrate时创建这些默认权限。这些权限与admin管理界面中的创建,删除,修改行为是一一对应的。
假设你有一个应用 foo ,其中有一个模型 Bar, 你可以用下述方法来测试基本权限:
add: user.has_perm('foo.add_bar')
change: user.has_perm('foo.change_bar')
delete: user.has_perm('foo.delete_bar')
权限模型( Permission model)一般不直接使用。
组Groups
组也是作为Model存在的:
@python_2_unicode_compatible
class Group(models.Model):
"""
Groups are a generic way of categorizing users to apply permissions, or
some other label, to those users. A user can belong to any number of
groups. A user in a group automatically has all 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. Beyond permissions, groups are a convenient way to categorize users to
apply some label, or extended functionality, to them. For example, you
could create a group 'Special users', and you could write code that would
do special things to those users -- such as giving them access to a
members-only portion of your site, or sending them members-only email
messages.
"""
name = models.CharField(_('name'), max_length=80, unique=True)
permissions = models.ManyToManyField(Permission,
verbose_name=_('permissions'), blank=True) objects = GroupManager() class Meta:
verbose_name = _('group')
verbose_name_plural = _('groups') def __str__(self):
return self.name def natural_key(self):
return (self.name,)
字段fields:
name:必需,80个字符或更少,例如, 'Awesome Users'。
permissions:ManyToManyField to Permission
group.permissions = [permission_list]
group.permissions.add(permission, permission, ...)
group.permissions.remove(permission, permission, ...)
group.permissions.clear()
Programmatically creating permissions
除了可以使用Model meta来创建权限,也可以直接用代码创建。
例如,为myapp应用中的BlogPost模型创建一个can_publish权限:
from myapp.models import BlogPost
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType content_type = ContentType.objects.get_for_model(BlogPost)
permission = Permission.objects.create(codename='can_publish',
name='Can Publish Posts',
content_type=content_type)
权限可以被赋予一个User对象通过它的user_permissions属性或者赋予一个Group通过它的permissions属性。
权限缓存
User的权限检查时是可以被缓存的,如果一个新权限被赋予一个User,如果再立即检查是不会被检查出来的。最简单的方法是重新fetch User对象。
from django.contrib.auth.models import Permission, User
from django.shortcuts import get_object_or_404 def user_gains_perms(request, user_id):
user = get_object_or_404(User, pk=user_id)
#权限检查会缓存现在的权限集
user.has_perm('myapp.change_bar') permission = Permission.objects.get(codename='change_bar')
user.user_permissions.add(permission) # 检查权限缓存集
user.has_perm('myapp.change_bar') # False # 请求新实例
user = get_object_or_404(User, pk=user_id) # Permission cache is repopulated from the database
user.has_perm('myapp.change_bar') # True ...
权限装饰器
permission_required(perm[, login_url=None, raise_exception=False])
检查用户是否具有某个权限,类似于@login_required()
from django.contrib.auth.decorators import permission_required
@permission_required('polls.can_vote', login_url='/loginpage/')
def my_view(request):
...
模板中的权限
user的的权限保存在模板变量 {{ perms }}中,是django.contrib.auth.context_processors.PermWrapper实例。
{{ perms.foo }}
上面的单属性是User.has_module_perms的代理。如果user拥有foo中的任一权限,则为True
{{ perms.foo.can_vote }}
上面的两级属性查询是User.has_perm的代理,如果用户拥有foo.can_vote权限则为True。
例如:
{% if perms.foo %}
<p>You have permission to do something in the foo app.</p>
{% if perms.foo.can_vote %}
<p>You can vote!</p>
{% endif %}
{% if perms.foo.can_drive %}
<p>You can drive!</p>
{% endif %}
{% else %}
<p>You don't have permission to do anything in the foo app.</p>
{% endif %}
或者:
{% if 'foo' in perms %}
{% if 'foo.can_vote' in perms %}
<p>In lookup works, too.</p>
{% endif %}
{% endif %}
Django用户认证系统(三)组与权限的更多相关文章
- django用户认证系统——拓展 User 模型
Django 用户认证系统提供了一个内置的 User 对象,用于记录用户的用户名,密码等个人信息.对于 Django 内置的 User 模型, 仅包含以下一些主要的属性: username,即用户名 ...
- django用户认证系统——拓展 User 模型2
Django 用户认证系统提供了一个内置的 User 对象,用于记录用户的用户名,密码等个人信息.对于 Django 内置的 User 模型, 仅包含以下一些主要的属性: username,即用户名 ...
- django用户认证系统——基本设置1
网站提供登录.注册等用户认证功能是一个常见的需求.因此,Django 提供了一套功能完整的.灵活的.易于拓展的用户认证系统:django.contrib.auth.在本教程中,我将向你展示 auth ...
- “Django用户认证系统”学习资料收集
首推追梦人物——Django用户认证系统 待续……
- django用户认证系统——重置密码7
当用户不小心忘记了密码时,网站需要提供让用户找回账户密码的功能.在示例项目中,我们将发送一封含有重置用户密码链接的邮件到用户注册时的邮箱,用户点击收到的链接就可以重置他的密码,下面是具体做法. 发送邮 ...
- django用户认证系统——修改密码6
再此之前我们已经完成了用户登录.注册.注销等功能,接下来让我们继续为用户提供修改密码的功能.该功能 Django 的 auth 应用也已经为我们提供,过程几乎和之前的登录功能完全一样. 编写修改密码模 ...
- django用户认证系统——登录4
用户已经能够在我们的网站注册了,注册就是为了登录,接下来我们为用户提供登录功能.和注册不同的是,Django 已经为我们写好了登录功能的全部代码,我们不必像之前处理注册流程那样费劲了.只需几分钟的简单 ...
- D django 用户认证系统
django认证系统包含三个部分:用户.权限和分组 安装 django项目默认启用了认证系统,如果不是使用django-admin.py创建项目的可以通过在settings配置文件里面的INSTALL ...
- 14:django 用户认证系统
django认证系统包含三个部分:用户.权限和分组 安装 django项目默认启用了认证系统,如果不是使用django-admin.py创建项目的可以通过在settings配置文件里面的INSTALL ...
随机推荐
- C++与Lua交互(五)
引言 要将C++中的对象类型映射到Lua中,就不得不要先了解Lua面向对象的机制.在这里,我们先看一下Lua面向对象的实现基础--metatable,再以此实现C++对象到Lua的映射. Lua面向对 ...
- C++与Lua交互(四)
引言 通过前几篇,我们已经对Lua的C API有了一定的了解,如lua_push*.lua_is*.lua_to*等等.用C++调用Lua数据时,我们主要运用lua_getglobal与lua_pus ...
- OpenCV3添加滑动条和鼠标事件到图形界面
鼠标事件和滑动条控制在计算机视觉和OpenCV中非常有用,使用这些控件,用户可以直接与图形界面交互,改变输入图像或者变量的属性值. /* In this section, we are going t ...
- PHP、Java、C#实现URI参数签名算法,确保应用与REST服务器之间的安全通信,防止Secret Key盗用、数据篡改等恶意攻击行为
简介 应用基于HTTP POST或HTTP GET请求发送Open API调用请求时,为了确保应用与REST服务器之间的安全通信,防止Secret Key盗用.数据篡改等恶意攻击行为,REST服务器使 ...
- nodejs npm install全局安装和本地安装的区别
npm的包安装分为本地安装(local).全局安装(global)两种,从敲的命令行来看,差别只是有没有-g而已,比如:代码如下:复制代码npm install # 本地安装npm install - ...
- 《WPF程序设计指南》读书笔记——第7章 Canvas
1.Canvas面板 using System; using System.Windows; using System.Windows.Controls; using System.Windows.M ...
- lazy instructor
Description A math instructor is too lazy to grade a question in the exam papers in which students a ...
- envi中多波段图层叠加layer stacking
Basic Tools——layer stacking 选择投影和输出的文件 波段1-7波段图层都叠加在一个文件中了
- NSTImer重复执行任务
问题 应用需要调度代码以在特定的时间执行.此外,你还想要重复执行任务. 解决方案 使用NSTimer调度代码以在特定的时间执行.为了使用NSTimer,你需要有日期对象与指向应用的运行循环的引用. 注 ...
- mybatis的javaType和ofType
都是指定对象的类型 不同的是当使用反向查询select从另一个maper文件中取出数据时必须用ofType 都可以为collection和association是指定对象的类型, 都不是必须写的, 只 ...