简体   繁体   English

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

[英]How to add custom permission to the User model in django?

in django by default when syncdb is run with django.contrib.auth installed, it creates default permissions on each model... like foo.can_change , foo.can_delete and foo.can_add. 在django中默认情况下,当安装了django.contrib.auth运行syncdb时,它会为每个模型创建默认权限...如foo.can_change,foo.can_delete和foo.can_add。 To add custom permissions to models one can add class Meta: under the model and define permissions there, as explained here https://docs.djangoproject.com/en/dev/topics/auth/#custom-permissions 要向模型添加自定义权限,可以在模型下添加类Meta:并在那里定义权限,如此处所述https://docs.djangoproject.com/en/dev/topics/auth/#custom-permissions

My question is that what should I do if I want to add a custom permission to the User model? 我的问题是,如果我想为User模型添加自定义权限,该怎么办? like foo.can_view. 喜欢foo.can_view。 I could do this with the following snippet, 我可以使用以下代码段执行此操作,

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()

But I want something that plays nicely with syncdb, for example the class Meta under my custom models. 但是我想要一些与syncdb很好地结合的东西,例如我自定义模型下的Meta类。 Should I just have these in class Meta: under UserProfile since that is the way to extend the user model. 我应该在MetaTlass类中使用这些,因为这是扩展用户模型的方法。 but is that the RIGHT way to do it? 但这是正确的方法吗? Wouldn't that tie it to UserProfile model? 它不会与UserProfile模型联系起来吗?

You could do something like this: 你可以这样做:

in the __init__.py of your Django app add: 在你的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)

我不认为这里有一个“正确”的答案,但我使用了与你完全相同的代码,除了我将Permission.objects.create更改为Permission.objects.get_or_create并且找到了与syncdb同步

An updated answer for Django 1.8. Django 1.8的更新答案。 The signal pre_migrate is used instead of pre_syncdb , since syncdb is deprecated and the docs recommend using pre_migrate instead of post_migrate if the signal will alter the database. 使用信号pre_migrate而不是pre_syncdb ,因为不推荐使用pre_migrate ,如果信号将改变数据库,则文档建议使用pre_migrate而不是post_migrate Also, @receiver is used to connect add_user_permissions to the signal. 此外, @receiver add_user_permissions用于将add_user_permissions连接到信号。

from django.db.models.signals import pre_migrate
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import models as auth_models
from django.contrib.auth.models import Permission
from django.conf import settings
from django.dispatch import receiver


# custom user related permissions
@receiver(pre_migrate, sender=auth_models)
def add_user_permissions(sender, **kwargs):
    content_type = ContentType.objects.get_for_model(settings.AUTH_USER_MODEL)
    Permission.objects.get_or_create(codename='view_user', name='View user', content_type=content_type)

This is a bit hacky but mentioning it here anyway for reference. 这有点hacky,但无论如何在此提及以供参考。

My site has a generic model called Setting , which stores various settings concerning the site I want certain users to be able to edit, without needing to go through me the developer (like registration limit, or an address, or the cost of items, etc). 我的网站有一个名为Setting的通用模型,它存储了我希望某些用户能够编辑的网站的各种设置,而无需通过我的开发人员(如注册限制,地址或项目成本等) )。

All the permissions that don't nicely map onto other models (eg "Send Password Reminder Email to Student", "Generate Payment Reconciliation Report", "Generate PDF Receipt"), which really just relate to pages that get viewed in the admin area, get dumped onto this Setting model. 所有权限都不能很好地映射到其他模型(例如“发送密码提醒电子邮件给学生”,“生成付款调节报告”,“生成PDF收据”),这些权限实际上只与在管理区域中查看的页面相关,转到此Setting模型。

For example, here's the model: 例如,这是模型:

class Setting(models.Model):
    name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(editable=False)
    description = models.TextField()
    value = models.TextField()
    class Meta:
        #for permissions that don't really relate to a particular model, and I don't want to programmatically create them.
        permissions = (
            ("password_reminder", "Send Password Reminder"),
            ("generate_payment_reconciliation_report", "Generate Payment Reconciliation Report"),
            ("generate_pdf_receipt", "Generate PDF Receipt"),
        )

Do each of those settings strictly relate to the Setting model? 这些设置中的每一个都与Setting模型严格相关吗? No, which is why I said this is a bit hacky. 不,这就是为什么我说这有点hacky。 But it is nice that I can now just dump all those permissions here, and Django's migration commands will take care of the rest. 但现在我可以在这里转储所有这些权限,这很好,Django的迁移命令将处理其余的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM