简体   繁体   中英

Override get_queryset based on django-guardian permissions

I am trying to override get_queryset based on the object permissions, which the users have from django guardian, so that only the objects are visible, which the users have permissions for.

def get_queryset(self, request):
    if request.user.is_superuser:
        qs = super(MyAdminInline, self).get_queryset(request)
        return qs  

    for item in MyModel.objects.all():
        for perm in get_perms(request.user, item):
            things_user_can_see = get_objects_for_user(request.user, perm)
            return things_user_can_see

Sadly, this literally does nothing and all of the items, regardless of the permissions that the users have, are visible.

Firstly, you need to understand what permissions are required for your view. Then, accordingly to those permissions fetch objects.

If you don't know permissions for object, then you can filter your objects, by all permissions related to model.

Docs for fetching:

from guardian.shortcuts import get_objects_for_user, get_perms_for_model

class MyAdminInline():
    def get_queryset(self, request):
        if request.user.is_superuser:
            qs = super(MyAdminInline, self).get_queryset(request)
            return qs  

        all_model_perms = get_perms_for_model(MyModel)
        return get_objects_for_user(request.user, all_model_perms)

And that's all! Without looping over every-single object, checking permissions and returning the wrong way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM