سؤال

I only want data to be sent using POST to this api endpoint. Is there a way to set which request methods are allowed?

class FooViewSet(viewsets.ModelViewSet):
    queryset = Foo.objects.all()
    serializer_class = FooSerializer
هل كانت مفيدة؟

المحلول

Do you need the whole ViewSet or will a normal GenericView be sufficient? You could use the CreateAPIView.

Example:

class FooCreate(generics.CreateAPIView):
    Model = Foo
    serializer_class = FooSerializer

EDIT:

If you do need to use a ViewSet, you could create a custom Router that will only handle post requests. Documentation here, including a read-only (i.e. get) example.

نصائح أخرى

There is probably a better solution, but what I did normally is

if request.method != 'POST':
       return Http404

but this seems to have the answer you need: https://docs.djangoproject.com/en/dev/topics/http/decorators/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top