Skip to content

Models

BaseObjectPermission

Bases: Model

Base ObjectPermission model.

Child classed should additionally define a content_object field and either user or group field.

See Also

UserObjectPermission and GroupObjectPermission

Source code in guardian/models/models.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class BaseObjectPermission(models.Model):
    """Base ObjectPermission model.

    Child classed should additionally define a `content_object` field and either `user` or `group` field.

    See Also:
        `UserObjectPermission` and `GroupObjectPermission`
    """

    permission = models.ForeignKey(Permission, on_delete=models.CASCADE)

    class Meta:
        abstract = True

    def __str__(self) -> str:
        return "{} | {} | {}".format(
            str(self.content_object), str(getattr(self, "user", False) or self.group), str(self.permission.codename)
        )

    def save(self, *args, **kwargs) -> None:
        """Save the current instance.

        Override this if you need to control the saving process.
        The `force_insert` and `force_update` parameters can be used to insist that the “save”
        must be an SQL insert or update statement, respectively (or equivalent for non-SQL backends).
        Normally, they should not be set.

        Other Parameters:
            force_insert (bool): If True, the save will be forced to be an insert.
            force_update (bool): If True, the save will be forced to be an update.
        """
        content_type = get_content_type(self.content_object)
        if content_type != self.permission.content_type:
            raise ValidationError(
                "Cannot persist permission not designed for "
                "this class (permission's type is %r and object's type is %r)"
                % (self.permission.content_type, content_type)
            )
        return super().save(*args, **kwargs)

save(*args, **kwargs)

Save the current instance.

Override this if you need to control the saving process. The force_insert and force_update parameters can be used to insist that the “save” must be an SQL insert or update statement, respectively (or equivalent for non-SQL backends). Normally, they should not be set.

Other Parameters:

Name Type Description
force_insert bool

If True, the save will be forced to be an insert.

force_update bool

If True, the save will be forced to be an update.

Source code in guardian/models/models.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def save(self, *args, **kwargs) -> None:
    """Save the current instance.

    Override this if you need to control the saving process.
    The `force_insert` and `force_update` parameters can be used to insist that the “save”
    must be an SQL insert or update statement, respectively (or equivalent for non-SQL backends).
    Normally, they should not be set.

    Other Parameters:
        force_insert (bool): If True, the save will be forced to be an insert.
        force_update (bool): If True, the save will be forced to be an update.
    """
    content_type = get_content_type(self.content_object)
    if content_type != self.permission.content_type:
        raise ValidationError(
            "Cannot persist permission not designed for "
            "this class (permission's type is %r and object's type is %r)"
            % (self.permission.content_type, content_type)
        )
    return super().save(*args, **kwargs)

UserObjectPermissionBase

Bases: BaseObjectPermission

Base class for creating object level permissions for users.

This class can be used as a base class for creating a custom model to manager user object-level permissions.

Attributes:

Name Type Description
user ForeignKey

The django user model that has the permission.

permission ForeignKey

Foreign key to the permission granted.

content_object (ForeignKey, GenericForeignKey)

A foreign Key to the model class that the permission will be granted for.

Example
from guardian.models import UserObjectPermissionBase

class OrgUserObjectPermission(UserObjectPermissionBase):
    """Organization Specific permissions."""

    class Meta(UserObjectPermissionBase.Meta):
        verbose_name = "Organization Permission"
        verbose_name_plural = "Organization Permissions"

    # Note: class attribute must be named content_object
    content_object = models.ForeignKey("myapp.Org", on_delete=models.CASCADE, db_column="org_object_id")
See Also
Source code in guardian/models/models.py
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
class UserObjectPermissionBase(BaseObjectPermission):
    """Base class for creating object level permissions for users.

    This class can be used as a base class for creating a custom model to
    manager user object-level permissions.

    Attributes:
        user (ForeignKey): The django user model that has the permission.
        permission (ForeignKey): Foreign key to the permission granted.
        content_object (ForeignKey, GenericForeignKey):
            A foreign Key to the model class that the permission will be granted for.

    Example:
        ```python
        from guardian.models import UserObjectPermissionBase

        class OrgUserObjectPermission(UserObjectPermissionBase):
            \"\"\"Organization Specific permissions.\"\"\"

            class Meta(UserObjectPermissionBase.Meta):
                verbose_name = "Organization Permission"
                verbose_name_plural = "Organization Permissions"

            # Note: class attribute must be named content_object
            content_object = models.ForeignKey("myapp.Org", on_delete=models.CASCADE, db_column="org_object_id")

        ```

    See Also:
        - [Django-Guardian Performance Tuning](https://django-guardian.readthedocs.io/en/stable/userguide/performance.html)
        - [How to override the default UserObjectPermission](https://django-guardian.readthedocs.io/en/stable/configuration.html#guardian-user-obj-perms-model)
    """

    user = models.ForeignKey(user_model_label, on_delete=models.CASCADE)

    objects = UserObjectPermissionManager()

    class Meta:
        abstract = True
        unique_together = ["user", "permission", "content_object"]

UserObjectPermission

Bases: UserObjectPermissionAbstract

The default implementation of the UserObjectPermissionAbstract model.

If GUARDIAN_USER_OBJ_PERMS_MODEL is not set at the beginning of the project, this model will be used. Uses Django's contenttypes framework to store generic relations.

See Also
Source code in guardian/models/models.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
class UserObjectPermission(UserObjectPermissionAbstract):
    """The default implementation of the UserObjectPermissionAbstract model.

    If `GUARDIAN_USER_OBJ_PERMS_MODEL` is not set at the beginning of the project, this model will be used.
    Uses Django's contenttypes framework to store generic relations.

    See Also:
        - [Django's Documentation on Abstract Base Models](https://docs.djangoproject.com/en/stable/topics/db/models/#abstract-base-classes)
        - [Django-Guardian Performance Tuning](https://django-guardian.readthedocs.io/en/stable/userguide/performance.html)
        - [How to override the default UserObjectPermission](https://django-guardian.readthedocs.io/en/stable/configuration.html#guardian-user-obj-perms-model)
    """

    class Meta(UserObjectPermissionAbstract.Meta):
        abstract = False
        indexes = [
            models.Index(fields=["permission", "user", "content_type", "object_pk"]),
            models.Index(fields=["user", "content_type", "object_pk"]),
        ]

GroupObjectPermissionBase

Bases: BaseObjectPermission

Base class for creating django-guardian groups.

This class can be used as a base class for creating a groups permission.

Attributes:

Name Type Description
group ForeignKey

A foreign key to the django auth group.

permission ForeignKey

Foreign key to the permission granted.

content_object (ForeignKey, GenericForeignKey)

A foreign Key to the model class that the permission will be granted for.

Example
from guardian.models import GroupObjectPermissionBase

class OrgGroupObjectPermission(GroupObjectPermissionBase):
    """Organization Groups."""

    class Meta(GroupObjectPermissionBase.Meta):
        verbose_name = "Organization Role"
        verbose_name_plural = "Organization Roles"

    content_object = models.ForeignKey("myapp.Org", on_delete=models.CASCADE, db_column="org_object_id")
See Also
Source code in guardian/models/models.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
class GroupObjectPermissionBase(BaseObjectPermission):
    """Base class for creating django-guardian groups.

    This class can be used as a base class for creating a groups permission.

    Attributes:
        group (ForeignKey): A foreign key to the django auth group.
        permission (ForeignKey): Foreign key to the permission granted.
        content_object (ForeignKey, GenericForeignKey):
            A foreign Key to the model class that the permission will be granted for.

    Example:
        ```python
        from guardian.models import GroupObjectPermissionBase

        class OrgGroupObjectPermission(GroupObjectPermissionBase):
            \"\"\"Organization Groups.\"\"\"

            class Meta(GroupObjectPermissionBase.Meta):
                verbose_name = "Organization Role"
                verbose_name_plural = "Organization Roles"

            content_object = models.ForeignKey("myapp.Org", on_delete=models.CASCADE, db_column="org_object_id")
        ```

    See Also:
        - [Django-Guardian Performance Tuning](https://django-guardian.readthedocs.io/en/stable/userguide/performance.html)
        - [How to override the default UserObjectPermission](https://django-guardian.readthedocs.io/en/stable/configuration.html#guardian-user-obj-perms-model)
    """

    group = models.ForeignKey(Group, on_delete=models.CASCADE)

    objects = GroupObjectPermissionManager()

    class Meta:
        abstract = True
        unique_together = ["group", "permission", "content_object"]

GroupObjectPermission

Bases: GroupObjectPermissionAbstract

The default implementation of the GroupObjectPermissionAbstract model.

If GUARDIAN_GROUP_OBJ_PERMS_MODEL is not set at the beginning of the project, this model will be used. Uses Django's contenttypes framework to store generic relations.

See Also
Source code in guardian/models/models.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
class GroupObjectPermission(GroupObjectPermissionAbstract):
    """The default implementation of the GroupObjectPermissionAbstract model.

    If `GUARDIAN_GROUP_OBJ_PERMS_MODEL` is not set at the beginning of the project, this model will be used.
    Uses Django's contenttypes framework to store generic relations.

    See Also:
        - [Django's Documentation on Abstract Base Models](https://docs.djangoproject.com/en/stable/topics/db/models/#abstract-base-classes)
        - [Django-Guardian Performance Tuning](https://django-guardian.readthedocs.io/en/stable/userguide/performance.html)
        - [How to override the default GroupObjectPermission](https://django-guardian.readthedocs.io/en/stable/configuration.html#guardian-user-obj-perms-model)
    """

    class Meta(GroupObjectPermissionAbstract.Meta):
        abstract = False
        indexes = [
            models.Index(fields=["permission", "group", "content_type", "object_pk"]),
            models.Index(fields=["group", "content_type", "object_pk"]),
        ]