Manual

Permission Function

The permission function is a callback associated with a model.

Using the model_permissions.backends.ObjectModelBackend the object permissions are extended with django.contrib.auth.models.User.user_permissions and django.contrib.auth.models.Group.permissions.

Tip

Use the same permissions as in your database and add your custom permissions to django.db.models.Options.permissions to handle both nicely.

There are 2 ways to define it:

  1. On the model itself:

    class MyModel(models.Model):
    
        owner = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)
    
        def get_permissions(self, user):
            if user == self.owner:
                return [
                    'myapp.change_mymodel',
                    'myapp.delete_mymodel',
                ]
    
  2. Using the MODEL_PERMISSIONS setting in your settings.py:

    It accepts functions and module paths.

    def get_mymodel_permissions(user, obj):
        if user in obj.moderator_set.all():
            return [
                'myapp.change_mymodel',
                'myapp.delete_mymodel',
            ]
    
    MODEL_PERMISSIONS = {
        AUTH_USER_MODEL: 'accounts.models.get_profile_permissions',
        'myapp.mymodel': get_mymodel_permissions,
    }
    

Note

When you define a permission function for your user model, keep in mind that it will receive 2 user objects! The user who is requesting permissions first and the user which he/she/it is requesting permissions for as second argument.