我想在一个抽象模型类上定义一些自定义权限,然后由所有子类继承,而不是给权限一个可以应用于任何子类模型类型的通用对象名,我想基本上使用子模型的verbose_name_plural
属性作为权限名称和描述的一部分(例如('view_classname', 'Can view classname')
),模拟Django的默认行为。
所以,我希望做的是这样的事情(由于verbose_name_plural
未在此上下文中定义,因此不起作用):
class AbstractModel(models.Model):
class Meta:
abstract = True
permissions = (
(u'view_%ss' % verbose_name_plural, u'Can view %s' % verbose_name_plural),
)
(此问题也在http://code.djangoproject.com/ticket/10686中描述,其中包含一个在权限定义中实现动态替换%(class)s
的补丁,但此修补程序从未被接受,我的生产环境不允许修补Django 。)
答案 0 :(得分:0)
你能用类装饰器而不是抽象模型类完成这个吗?
def with_view_perm(cls):
vn = cls.Meta.verbose_name_plural
perms = (('view_%s' % vn, 'Can view %s' % vn),)
cls.Meta.perms += perms
return cls
@with_view_perm
class Child(models.Model):
class Meta:
verbose_name_plural = 'children'
perms = (('change_children', 'Can change children'),)
答案 1 :(得分:0)
它已经过时了 - 但是为了将来的参考 - 现在所需的行为是开箱即用的(Django 1.9)
考虑具有适当权限的抽象模型:
class DetailContentLifecycleClassModel (models.Model):
class Meta:
abstract=True
permissions = (
('can_change_content', 'Change content of the model'),
('can_submit_for_approval', 'Ask for final check and publishing'),
('can_publish_content', 'Publish the model as a new version'),
)
继承如下:
class Test_Details (DetailContentLifecycleClassModel):
name = models.CharField(max_length=200)
class Test_Details2 (DetailContentLifecycleClassModel):
name = models.CharField(max_length=200)
Permssions创建如下:
from playground.models import Test_Details
from django.contrib.auth.models import User, Permission
tmp = Permission.objects.filter()
结果(这正是所需的):
playground | test_ details | Can add test_ details
playground | test_ details | Change content of the model
playground | test_ details | Publish the model as a new version
playground | test_ details | Ask for final check and publishing
playground | test_ details | Can change test_ details
playground | test_ details | Can delete test_ details
playground | test_ details2 | Can add test_ details2
playground | test_ details2 | Change content of the model
playground | test_ details2 | Publish the model as a new version
playground | test_ details2 | Ask for final check and publishing
playground | test_ details2 | Can change test_ details2
playground | test_ details2 | Can delete test_ details2
答案 2 :(得分:0)
另一种更新的方法是在基类的Meta中设置default_permissions。
另外请注意,在执行此操作时,您需要制作并运行迁移才能使其生效。