[Django]-Django โ€“ Pass related object as variable in user_passes_test mixin

2๐Ÿ‘

โœ…

If you are using DetailView then you can implement the get_queryset method in the view:

class EventDetail(DetailView):
    model = Event

    def get_queryset(self):
        queryset = super(DetalView, self).get_queryset()
        return queryset.filter(client=self.request.user)

This would make sure that the Event objects are restricted to the user as a client only.

I am not sure what URL are you using to access the Event and why there is just OneToOne relation between Event and User. But if it is a OneToOne relation then the queryset after this implementation will contain only one object. (which might or might not be the primary key using which you are accessing this event).

๐Ÿ‘คAKS

1๐Ÿ‘

I finally got it, I think it took me writing it out to realize I could just put an if / else condition on the queryset like this:

def get_queryset(self):
    queryset = super(DetailView, self).get_queryset()
    if self.request.user.is_staff:
        return queryset
    else:
        return queryset.filter(client=self.request.user)

Thank you AKS!

๐Ÿ‘คbrandondavid

Leave a comment