Xar
Xar

Reputation: 7940

DRF: how to not allow create() in Serializer

I'm working with DRF and have a ViewSet where I want to allow all the possible actions (list, details, update, delete), except create().

This is what I have for the moment:

class FooViewSet(viewsets.ModelViewSet):

    queryset = Foo.objects.order_by('-date_added').all()
    serializer_class = FooSerializer

    def create(self, request):
        return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)

    def update(self, request, pk=None):
        version = get_object_or_404(Foo, pk=pk)
        html = request.data.get('html')
        version.update_content(html)
        return Response(data={
            'id': version.id,
            'name': version.name,
            'description': version.description,
            'html': version.content,
        }, status=status.HTTP_200_OK)

I know I could make the serializer inherit from ReadOnlyModelViewSet but then I wouldn't be able to update it.

So what is the cleanest way of not allowing to create()?

Upvotes: 2

Views: 454

Answers (2)

Jun Zhou
Jun Zhou

Reputation: 1117

As stated in this answer, you can limit the allowed methods by adding http_method_names in any class view. http_method_names is an attribute in Django default view class, you can find the detailed definition in this link.

Take your code as an example, if you want to exclude create(refer to 'post' method) operation, you can do the following:

class FooViewSet(viewsets.ModelViewSet):
    queryset = Foo.objects.order_by('-date_added').all()
    serializer_class = FooSerializer
    http_method_names = ['head', 'get', 'put', 'patch', 'delete']

Upvotes: 2

Massimo Costa
Massimo Costa

Reputation: 1860

from rest framework's code

class ModelViewSet(mixins.CreateModelMixin,
               mixins.RetrieveModelMixin,
               mixins.UpdateModelMixin,
               mixins.DestroyModelMixin,
               mixins.ListModelMixin,
               GenericViewSet):

you can create your viewset without the CreateModelMixin

class MyViewSet(mixins.RetrieveModelMixin,
               mixins.UpdateModelMixin,
               mixins.DestroyModelMixin,
               mixins.ListModelMixin,
               GenericViewSet):

Upvotes: 1

Related Questions