内容简介: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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Writing Apache Modules with Perl and C
Lincoln Stein、Doug MacEachern / O'Reilly Media, Inc. / 1999-03 / USD 39.95
Apache is the most popular Web server on the Internet because it is free, reliable, and extensible. The availability of the source code and the modular design of Apache makes it possible to extend Web......一起来看看 《Writing Apache Modules with Perl and C》 这本书的介绍吧!