python – 如何在django中为用户模型添加自定义权限?

栏目: Python · 发布时间: 7年前

内容简介:http://stackoverflow.com/questions/7724265/how-to-add-custom-permission-to-the-user-model-in-django

在django中默认情况下,syncdb运行时安装了django.contrib.auth,它会为每个模型创建默认权限,如foo.can_change,foo.can_delete和foo.can_add.要向模型添加自定义权限,可以添加类Meta:在模型下,并在其中定义权限,如此处所述

我的问题是,如果我要为用户模型添加自定义权限,该怎么办?像foo.can_view.我可以用下面的代码片段来实现,

ct = ContentType.objects.get(app_label='auth', model='user')
perm = Permission.objects.create(codename='can_view', name='Can View Users', 
                                  content_type=ct)
perm.save()

但是我想要一些可以很好地与syncdb一起玩的东西,例如我的自定义模型下的Meta类.我应该在类Meta中有这些:在UserProfile下,因为这是扩展用户模型的方式.但是是否正确的方式呢?不会把它绑定到UserProfile模型?

你可以这样做:

在Django应用的__init__.py中添加:

from django.db.models.signals import post_syncdb
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import models as auth_models
from django.contrib.auth.models import Permission

# custom user related permissions
def add_user_permissions(sender, **kwargs):
    ct = ContentType.objects.get(app_label='auth', model='user')
    perm, created = Permission.objects.get_or_create(codename='can_view', name='Can View Users', content_type=ct)
post_syncdb.connect(add_user_permissions, sender=auth_models)

http://stackoverflow.com/questions/7724265/how-to-add-custom-permission-to-the-user-model-in-django


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Transcending CSS

Transcending CSS

Andy Clarke、Molly E. Holzschlag / New Riders / November 15, 2006 / $49.99

As the Web evolves to incorporate new standards and the latest browsers offer new possibilities for creative design, the art of creating Web sites is also changing. Few Web designers are experienced p......一起来看看 《Transcending CSS》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

MD5 加密
MD5 加密

MD5 加密工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具