django权限模块

1.models.py
添加class Meta:permissions来使权限可以通过django管理。
当同步到数据库后,才能生效


class Customer(models.Model):
    qq = models.CharField(max_length=64, unique=True)

    class Meta:
        permissions = (
            ('can_del_customer', '可以删除用户'),
        )

数据库同步:

PS D:\python\stu_crm> python.exe .\manage.py makemigrations                                            
Migrations for 'stucrm':                                                                               
  stucrm\migrations\0002_auto_20170625_1005.py                                                         
    - Change Meta options on customer                                                                  
PS D:\python\stu_crm> python.exe .\manage.py migrate                                                   
Operations to perform:                                                                                 
  Apply all migrations: admin, auth, contenttypes, sessions, stucrm                                    
Running migrations:                                                                                    
  Applying stucrm.0002_auto_20170625_1005... OK                                                        
PS D:\python\stu_crm>                                                                                  

django显示效果

django权限模块_第1张图片

2.权限如何验证
注意权限选项属于django的user表,用has_perm控制

In [1]: from stucrm import models

In [2]: u1=models.UserProfile.objects.last()

In [3]: u1
Out[3]: 

In [11]: u2=models.User.objects.last()

In [12]: u2
Out[12]: 

In [13]: u2.has_perm('can_del_customer')
Out[13]: False

In [14]: u2.has_perm('stucrm.can_del_customer')
Out[14]: True

3.较好的方式就是通过装饰器去实现权限功能。

4.权限优化
将权限存至models,并进行migrate
D:\python\stu_crm\stucrm\models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=64)
    class Meta:
        permissions = (
            ('view_customer_list', '查看用户列表'),
            ('view_customer_info', '查看用户详情'),
            ('edit_own_customer_info', '可以修改自己的客户的信息'),
        )

5.配置

定义监控选项具体的关联关系

# D:\python\stu_crm\stucrm\permissions.py
perm_dic = {
    'view_customer_list': ['customer_list','GET',[]],
    'view_customer_info': ['customer_detail','GET',[]],
    'edit_own_customer_info': ['customer_detail','POST',['test']],
}
# D:\python\stu_crm\stucrm\urls.py
url(r'^customers/(\d+)/$', views.customer_detail, name='customer_detail'),

# 实现url name代理固定域名
# D:\python\stu_crm\templates\crm\customers.html
"{% url 'customer_detail' item.id %}">{{ item.id }}


# D:\python\stu_crm\stucrm\urls.py
urlpatterns = [
    url(r'^$', views.dashboard),
    url(r'^customers/$', views.customers, name='customer_list'),
    url(r'^customers/(\d+)/$', views.customer_detail, name='customer_detail'),
]

引用permissions并采用装饰器的方式添加验证权限

from stucrm.permissions import check_permission
@check_permission

你可能感兴趣的:(django权限模块)