allow post requests in django REST framework
我正在使用django REST框架创建一个简单的rest api。 我通过向api发送GET请求成功获得了响应,但由于我想发送POST请求,django rest框架默认不允许POST请求。
如图像(下图)中仅允许GET,HEAD,OPTIONS但不允许POST请求
views.py中的GET和POST方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from profiles_api import serializers from rest_framework import status # Create your views here. class HelloApiView(APIView): """Test APIView""" #Here we are telling django that the serializer class for this apiViewClass is serializer.HelloSerializer class serializer_class = serializers.HelloSerializer def get(self, request, format=None): """Retruns a list of APIViews features.""" an_apiview = [ 'Uses HTTP methods as fucntion (get, post, patch, put, delete)', 'It is similar to a traditional Django view', 'Gives you the most of the control over your logic', 'Is mapped manually to URLs' ] #The response must be as dictionary which will be shown in json as response return Response({'message': 'Hello!', 'an_apiview': an_apiview}) def post(self,request): """Create a hello message with our name""" serializer = serializer.HelloSerializer(data=request.data) if serializer.is_valid(): name = serializer.data.get('name') message = 'Hello! {0}'.format(name) return Response({'message':message}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) |
How to allow POST requests in django REST framework?
代码的问题是,您在
要解决,只需更正
1 2 3 4 5 6 | class HelloApiView(APIView): def get(self, request, format=None): return Response() def post(self, request): return Response() |