Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-filter: extend filter query with request.user

I'm need to add an additional filter property (in the background) to a django-filter request.

My Model:

class Event(models.Model):
  name=models.CharField(max_length=254)
  location=models.ForeignKey(Place)
  invited_user=models.ManyToManyField(User,null=True, blank=True)

With a filter those entries with the same location can be filtered. This is working.

Further on I have to exclude all those entries where the invited_user is not the request.user (choosing this filter property is only possible if the user has permissions).

Is this possible with django-filter, and if yes how?

My filter Class: import django_filters from models import Event

class EventFilter(django_filters.FilterSet):
    class Meta:
        model = Event
        fields = ['location']

My work is based on: How do I filter tables with Django generic views?

like image 484
user3316786 Avatar asked Aug 31 '14 20:08

user3316786


1 Answers

you can access the request object in FilterSet.qs property.

class EventFilter(django_filters.FilterSet):
    class Meta:
        model = Event
        fields = ['location']
    
    @property
    def qs(self):
        queryset=super(EventFilter, self).qs
        if request.user.has_perm("app_label.has_permission"):       
            return queryset.exclude(invited_user!=self.request.user)
        return queryset      

docs https://rpkilby.github.io/django-filter/guide/usage.html#filtering-the-primary-qs

like image 164
udeep shrestha Avatar answered Sep 22 '22 07:09

udeep shrestha