django-rules
django-rules copied to clipboard
Hide objects from changelist in admin if user has no view_permission
Hi, i'm not sure if i understand the docs correctly, but i had the expectation that all items which have no view permission from the user would be hidden in django-admin's changelist. That is not the case in my current setup.
I did the following:
- use
RulesModel
instead django'sModel
class. - added
rules_permissions
to the Model'sMeta
with a perdicate for each ofadd
,view
,change
anddelete
according to my needs. - use
ObjectPermissionsModelAdmin
instead ofModelAdmin
in the admin. - Checking with User.has_perm works as intended
When displaying the changelist, these predicates get called with obj=None
.
I got it working by overriding the get_queryset
method of ObjectPermissionsModelAdmin
:
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
# remove all items from the queryset if the user has no view_permission
item_pks_to_remove = [item.pk for item in qs if not self.has_view_permission(request, item)]
qs = qs.exclude(pk__in=item_pks_to_remove)
return qs
Here's my question: I don't have any clue if this has some unforseen consequences that could break something. Is there a better way to do it? Or is my setup wrong? Maybe i've missed something to exclude the items without view_permission. Looking at the sources, I'm pretty confident, that the items are not hidden by default, but not sure.
Was looking for something like this. It is perhaps too slow to check for permissions per object in the queryset. What if you have millions of rows of data for a model?