1

I'm filtering real estates queryset dependent on user status and district (last one with GET param).

In views.py I have this:

class RealEstateView(APIView):
 serializer_class = RealEstateSerializer
 permission_classes = [RealEstatePermission]
 def get(self, request):
 district = self.request.query_params.get('pk')
 if district:
 serializer = RealEstateSerializer(RealEstate.objects.filter(owner_id=district), many=True)
 else:
 serializer = RealEstateSerializer(RealEstate.objects.all(), many=True)
 return Response(serializer.data)

If user is superuser, he have access to all information. If user in not superuser, he can get access only to real estates from district which he is responsible. If user is responsible to district with id=1, but sends a get param with id=2, I need to raise an exception. But the problem is I don't know how to get access to get parameter in has_permission function. Doing this inside views get function seems not good idea.

I already tried request.resolver_match.kwargs.get('id') and view.kwargs.get('id'), both of them are empty.

in permissions.py:

class RealEstatePermission(permissions.BasePermission):
 def has_permission(self, request, view):
 if request.user.is_authenticated:
 if request.user.is_staff:
 return True
 ## HERE I need something like request.user.district.id == kwargs('id')
 if request.user.role == 'district_municipality':
 return True

Using Django 3.0.5 and DRF 3.11.0.

Thank you for your help.

asked Apr 24, 2020 at 17:09
2
  • Why do you want to raise an exception? Mb you should not get district by get params and get them by yourself on backend? You have a user object that made the request and you can get his district ease. If the user is superuser you can allow him all Commented Apr 24, 2020 at 17:45
  • @AndreyRF, there are additional users category that can get access to data for read-only purposes. They are not superusers, but they can filter data by district. I'm just trying to avoid if-else conditions in view. Commented Apr 24, 2020 at 17:58

2 Answers 2

2

To get access to get parametersfrom url query you can use GET dict.

Example

url:

/district?id=2

access:

district_id = request.GET['id']
answered Apr 24, 2020 at 19:28
Sign up to request clarification or add additional context in comments.

Comments

1

You can use this as well:

Url:
/district?id=2
Access:
district_id = view.kwargs['id']
j__carlson
1,3583 gold badges14 silver badges22 bronze badges
answered Nov 28, 2021 at 18:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.