How to add custom permission to the User model in django?

后端 未结 4 1026
我寻月下人不归
我寻月下人不归 2021-02-12 15:53

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.

4条回答
  •  野性不改
    2021-02-12 16:33

    This is a bit hacky but mentioning it here anyway for reference.

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

    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.

    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? No, which is why I said this is a bit 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.

提交回复
热议问题