I want that User objects have no permission besides read for a model Foo, and then to have a Group that has all permissions. How do I do this?
Context: what I thought was I should make permissions restricted by default, but I haven’t found any examples of that and since it is a very common task I don’t think I’m going about this right.
You need to have code assocated with every view to enforce permissions. This can be done in the “common case” using the permission_required
decorator for function-based views, or the PermissionRequiredMixin for class-based views. You also have a variety of other functions and methods you can use for more complex situations.
But the bottom line is that views are “permissive” by default. The work needs to be done on every view that needs to enforce some type of limitation.
1 Like
I’m sorry, I still don’t understand where permissions are set. Borrowing from the example you linked:
from django.contrib.auth.mixins import PermissionRequiredMixin
class MyView(PermissionRequiredMixin, View):
permission_required = "polls.add_choice"
# Or multiple of permissions:
permission_required = ["polls.view_choice", "polls.change_choice"]
How do I determine that users will not have the polls.change_choice
permission unless they belong to a certain group?
Someone assigns them.
You don’t assign it to them.
Permissions do not get assigned to User or Group objects automatically. Something needs to assign the Permission object to those entitites.
(Note: The “admin” or “superuser” account passes all permission tests without any individual permissions explicitly being assigned.)
1 Like
So by default User/Group objects will have no permissions, and permissions will be added in specific views/commands?
And if I want everyone to be able to read a model, but not create/update/delete it, is the best approach to simply not check permissions in the “read” views?
That is correct.
Yes. You can use the admin for this, or you can create a custom view to allow for the assignment of permissions.
Correct. That’s the “common case”.
However, think “views” here, not models. You could have two views on the same model, one allowing unrestricted access, the other limited access. The point is that you are restricting access to a view, not a model.
Also, what a view chooses to display doesn’t necessarily need to have any relationship to the permission being tested.
1 Like