Debian Codegraph @

docs/userguide/assign.md

raw
1 ---
2 title: Object Permissions
3 description: How to assign object permissions.
4 ---
5
6 # Assigning Object Permissions
7
8 Django Guardian makes assigning object permissions simple once permissions are created for models.
9
10 ## Prepare permissions
11
12 Take the below example model:
13
14 ``` python
15 class Task(models.Model):
16 summary = models.CharField(max_length=32)
17 content = models.TextField()
18 reported_by = models.ForeignKey(User, on_delete=models.CASCADE)
19 created_at = models.DateTimeField(auto_now_add=True)
20 ```
21
22 ... and we want to be able to set custom permission *assign_task*.
23 We can let Django know about our custom permissions by adding a `permissions`
24 tuple to `Meta` class and our final model could look like:
25
26 ``` python
27 class Task(models.Model):
28 summary = models.CharField(max_length=32)
29 content = models.TextField()
30 reported_by = models.ForeignKey(User, on_delete=models.CASCADE)
31 created_at = models.DateTimeField(auto_now_add=True)
32
33 class Meta:
34 permissions = (
35 ('assign_task', 'Assign task'),
36 )
37 ```
38
39 !!! note
40
41 If using inheritance,
42 the `Meta` class with the custom permissions
43 **should** live in a abstract class.
44 We recommend users to read the section "[Meta inheritance](https://docs.djangoproject.com/en/stable/topics/db/models/#meta-inheritance)"
45 from the Django documentation.
46
47 After we call management commands `makemigrations` and `migrate` our
48 *assign_task* permission would be added to default set of permissions.
49
50 !!! note
51
52 By default, Django adds 4 permissions for each registered model:
53
54 - *add_modelname*
55 - *change_modelname*
56 - *delete_modelname*
57 - *view_modelname*
58
59 (where *modelname* is a simplified name of our model's class). See
60 [https://docs.djangoproject.com/en/stable/topics/auth/default/#default-permissions](https://docs.djangoproject.com/en/stable/topics/auth/default/#default-permissions)
61 for more detail.
62
63 There is nothing new here since creation of permissions is [handled by
64 django](https://docs.djangoproject.com/en/stable/topics/auth/). Now we
65 can move to `assigning object permissions <assign-obj-perms>`
66
67 ## Using shortcuts
68
69 We can assign permissions for any user or group and object pairs
70 using the convenient function: `guardian.shortcuts.assign_perm()`
71
72 ### For a single object
73
74 Continuing our example we now can allow Joe user to assign some task:
75
76 ``` python
77 >>> from django.contrib.auth.models import User
78 >>> boss = User.objects.create(username='Big Boss')
79 >>> joe = User.objects.create(username='joe')
80 >>> task = Task.objects.create(summary='Some job', content='', reported_by=boss)
81 >>> joe.has_perm('assign_task', task)
82 False
83 ```
84
85 Well, not so fast Joe, let us create an object permission finally:
86
87 ``` python
88 >>> from guardian.shortcuts import assign_perm
89 >>> assign_perm('assign_task', joe, task)
90 >>> joe.has_perm('assign_task', task)
91 True
92 ```
93
94 This case doesn't really differ for group permissions assignment.
95 The only difference is we have to pass a `Group` instance rather than `User`.
96
97 ``` python
98 >>> from django.contrib.auth.models import Group
99 >>> group = Group.objects.create(name='employees')
100 >>> assign_perm('change_task', group, task)
101 >>> joe.has_perm('change_task', task)
102 False
103 >>> # Well, joe is not yet within an *employees* group
104 >>> joe.groups.add(group)
105 >>> joe.has_perm('change_task', task)
106 True
107 ```
108
109 ### For multiple objects
110
111 You can assign a permission to a single user or group across many objects at
112 once by passing a QuerySet as the `obj` argument:
113
114 ``` python
115 >>> tasks = Task.objects.filter(reported_by=boss)
116 >>> assign_perm('change_task', joe, tasks)
117 ```
118
119 ### For multiple users or groups
120
121 You can assign a permission on a single object to many users or groups at once
122 by passing a QuerySet as the `user_or_group` argument:
123
124 ``` python
125 >>> users = User.objects.filter(groups__name='employees')
126 >>> assign_perm('change_task', users, task)
127 ```
128
129 ## Using model managers
130
131 For more direct control you can call methods on the object-permission model
132 manager instead of going through the shortcut. First, obtain the permission
133 model for your object:
134
135 ``` python
136 >>> from guardian.utils import get_user_obj_perms_model, get_group_obj_perms_model
137 >>> UserObjectPermission = get_user_obj_perms_model(task)
138 >>> GroupObjectPermission = get_group_obj_perms_model(task)
139 ```
140
141 ### For a single object
142
143 ``` python
144 >>> UserObjectPermission.objects.assign_perm('change_task', joe, task)
145 ```
146
147 For a group:
148
149 ``` python
150 >>> GroupObjectPermission.objects.assign_perm('change_task', group, task)
151 ```
152
153 ### For multiple objects
154
155 Use `bulk_assign_perm` to assign a permission to one user or group across a
156 QuerySet of objects:
157
158 ``` python
159 >>> tasks = Task.objects.filter(reported_by=boss)
160 >>> UserObjectPermission.objects.bulk_assign_perm('change_task', joe, tasks)
161 ```
162
163 ### For multiple users or groups
164
165 Use `assign_perm_to_many` to assign a permission on one object to many users or
166 groups at once:
167
168 ``` python
169 >>> users = User.objects.filter(groups__name='employees')
170 >>> UserObjectPermission.objects.assign_perm_to_many('change_task', users, task)
171 ```
172
173 ## Limitations
174
175 !!! warning
176
177 **No bulk global permissions.** Passing a list or QuerySet of users/groups
178 without an object is not supported. Assign global permissions one
179 user/group at a time.
180
181 !!! warning
182
183 **No dual-bulk operations.** You cannot pass lists for both
184 `user_or_group` *and* `obj` at the same time. One side must be a single
185 instance. Passing lists for both raises
186 `guardian.exceptions.MultipleIdentityAndObjectError`.
187
188 !!! note
189
190 **Bulk operations do not fire `post_save` signals.** Bulk assignments use
191 `bulk_create()` internally, so per-object `post_save` signals are not
192 sent. If you rely on signals, assign permissions individually instead.
193
194 ## Assigning Permissions inside Signals
195
196 Note that the Anonymous User is created before the Permissions are
197 created. This may result in Django signals, e.g. `post_save` being sent
198 before the Permissions are created. You will need to take this into an
199 account when processing the signal.
200
201 ``` python
202 @receiver(post_save, sender=User)
203 def user_post_save(sender, **kwargs):
204 """
205 Create a Profile instance for all newly created User instances. We only
206 run on user creation to avoid having to check for existence on each call
207 to User.save.
208 """
209 user, created = kwargs["instance"], kwargs["created"]
210 if created and user.username != settings.ANONYMOUS_USER_NAME:
211 from profiles.models import Profile
212 profile = Profile.objects.create(pk=user.pk, user=user, creator=user)
213 assign_perm("change_user", user, user)
214 assign_perm("change_profile", user, profile)
215 ```
216
217 The check for `user.username != settings.ANONYMOUS_USER_NAME` is
218 required otherwise the `assign_perm` calls will occur when the Anonymous
219 User is created, however before there are any permissions available.