Home > Mobile >  How to properly handle request based on user's permissions Django
How to properly handle request based on user's permissions Django

Time:11-10

Using Django I have a class based view to get a list of items from my database. Thing is that this list should not be accessible to every user. A user that does not have admin or is_staff privileges should be able to see all items, whereas a regular account without this privilege will have access only to their items.

I was wondering how I should implement this.

Have a class based view where I check if the user is an admin and if so get all items back. And have another class based view that checks if the user is not an admin and gets all items back for only that user.

or

Have one class based view where I check if the user is admin and not admin and that one class based view handles the request differently depending on the 2 different scenarios.

I'm not sure what the "Django way" is but I would naturally go with the 2nd approach but thought I'd ask just in case.

CodePudding user response:

If the "Django way" is the most simplest, readable, and easiest, I think that is overwrite the get_queryset method in one class based view:


class MyView(generic.ListView):
    template_name = 'my-template.html'
    paginate_by = 25

    def get_queryset(self):
        queryset = MyModel.objects
        # I dont remember if a superser is already staff
        # In this case this can be replaced by: if self.request.user.is_staff: only
        if self.request.user.is_staff or self.request.user.is_superuser:
            queryset = queryset.filter(...filters...)
        else:
            queryset = queryset.filter(...other filters...)

        return queryset


  • Related