Question

I fail at making django-filter and django-guardian work together. What I need is an ItemsFilterView that lets the user list and filter all items that she has permission to view. Below are the parts of my code of which I think are most relevant. I can add more on request.

# filters.py
class ItemFilterSet(FilterSet):
    class Meta:
        model = Item

# views.py
class ItemFilterView(FilterView):
    filterset_class = ItemFilterSet

# urls.py
url(r'^items/$', ItemFilterView.as_view(), name='item_list'),

I think get_objects_for_user(request.user, 'view_item') should be used to narrow the queryset to only the permitted items before django-filter gets its hands on them, but I do not find the right place to add it.

Was it helpful?

Solution

I found the right location to add the logic:

# views.py
class ItemFilterView(FilterView):
    filterset_class = ItemFilterSet

    def get_queryset(self):
        qs = Item.objects.all()
        qs = get_objects_for_user(self.request.user, 'view_item', qs)
        return qs
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top