django-rules icon indicating copy to clipboard operation
django-rules copied to clipboard

Hide objects from changelist in admin if user has no view_permission

Open dzerrenner opened this issue 4 years ago • 1 comments

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's Model class.
  • added rules_permissions to the Model's Meta with a perdicate for each of add, view, change and delete according to my needs.
  • use ObjectPermissionsModelAdmin instead of ModelAdmin 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.

dzerrenner avatar Dec 22 '20 21:12 dzerrenner

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?

keyvanm avatar Feb 03 '21 01:02 keyvanm