如何在 Django 抽象模型类中动态命名权限?
我想在抽象模型类上定义一些自定义权限,然后由所有子类继承,而不是为权限提供可应用于任何子类模型类型的通用对象名称,我想本质上使用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。)
I want to define some custom permissions on an abstract model class that would then be inherited by all child classes, and rather than give the permissions a generic object name that could apply to any subclassed model type, I would like to essentially use the verbose_name_plural
property of the child model as part of the permission names and description (e.g. ('view_classname', 'Can view classname')
), emulating Django's default behavior.
So, what I would be hoping to do would be something like this (which doesn't work, since verbose_name_plural
is not defined in this context):
class AbstractModel(models.Model):
class Meta:
abstract = True
permissions = (
(u'view_%ss' % verbose_name_plural, u'Can view %s' % verbose_name_plural),
)
(This problem is also described at http://code.djangoproject.com/ticket/10686, which includes a patch that implements dynamic replacement of %(class)s
in permission definitions, but this patch was never accepted and my production environment does not allow for patching Django.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用类装饰器而不是抽象模型类来完成此任务吗?
Could you accomplish this with a class decorator instead of an abstract model class?
它很旧 - 但为了将来的参考 - 现在所需的行为是开箱即用的(Django 1.9)
考虑这个具有适当权限的抽象模型:
当像这样继承时:
权限创建如下:
结果(这正是原来的内容)通缉):
It's old - but for future reference - the desired behaviour is working out of the box now (Django 1.9)
Consider this abstract model with the appropriate permissions:
When inheriting like this:
The Permssions are created as following:
Result (which is exactly what was wanted):
另一种较新的方法是在基类的 Meta 中设置 default_permissions。
另请注意,执行此操作时,您需要进行并运行迁移才能使其生效。
The other newer way of doing this is to set default_permissions in the Meta on your base class.
Also be aware that when doing that you to make and run migrations for it to take effect.