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.
2 Answers 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']
Comments
You can use this as well:
Url:
/district?id=2
Access:
district_id = view.kwargs['id']
get paramsand 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