Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with Django rest-framework DjangoModelPermissions allowing any authenticated user

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

like image 484
Fabiot Avatar asked Sep 02 '14 16:09

Fabiot


People also ask

Which authentication is best in Django REST framework?

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.


1 Answers

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

like image 73
RaamVijay Avatar answered Oct 29 '22 04:10

RaamVijay