I am trying to use DjangoModelPermissions and it does not seem to work properly.
This is the code:
class TestViewSet(viewsets.ModelViewSet):
model = Test
serializer_class = serializers.TestSerializer
permission_classes = (permissions.DjangoModelPermissions,)
def create(self, request):
response_data = {}
response_data['type'] = 'error'
data=json.loads(request.raw_post_data)
test = Test.objects.create(name=data['name'],\
description=data['description'],\
start_date=data['start_date'],\
end_date=data['end_date'])
#save changes
test.save()
return Response({'status': 'ok', "result": test.id})
I don't think it makes any difference in this case but I am using django_mongodb_engine.
I have a user that has no permissions, and it is able to create Test instances. On the other hand, how can I block also GET so just users with the right permissions can perform that action?
Thanks
And these are all provided by drf(django rest framework) and other than these like oauth, oauth2 based authentication are provided by the efforts of the community with help of other python packages. And they can be easily used in the production environment.
The reason for DjangoModelPermissions is not working here is clearly explained in the DRF docs
"This permission must only be applied to views that have a .queryset property or get_queryset() method."
Check the docs here
The solution is:
Add queryset to your model
class TestViewSet(viewsets.ModelViewSet):
serializer_class = serializers.TestSerializer
permission_classes = (permissions.DjangoModelPermissions,)
queryset = Test.objects.all()
or if you want to override the default queryset method use this method as you like
def get_queryset(self):
return super().get_queryset()
Also, I noticed you don't have to specify the model in your ModelViewSet. If you specify your Test model in TestSerializer you only have to specify the serializer in ModelViewSet that's how DRF works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With