我知道有类似的问题,但我已经看过了所有的问题,都没有找到正确的答案。
我的APIView中有一个Question模型和POST方法,如下所示:
def post(self, request):
"""Create a new question"""
description = request.data['description']
question_type = request.data['type']
answers_to_close = request.data['to_close']
question = Question.objects.create(
description=description,
question_type=question_type,
answers_to_close=answers_to_close
)
return Response({
'status': 'SUCCESS', 'question_id': question.id,
'message': 'New question has been created successfully!',
'question': f"'{description}'"
})它工作得很好,但我也想添加一个在一个请求中创建多个问题的可能性。我尝试了这样的方法( APIView的另一个实例
def post(self, request, **kwargs):
"""Create a session of questions"""
session = kwargs['session']
description = request.data['description']
question_type = request.data['type']
answers_to_close = request.data['to_close']
Question.objects.create(
description=description,
question_type=question_type,
answers_to_close=answers_to_close,
session=session
)
return Response({
'status': 'SUCCESS', 'session': session,
'message': 'A new session has been created!'
})所以当我尝试这个curl请求时:
curl -X POST http://127.0.0.1:8000/api/sessions/create/21383/ --data
['description=Am I Strong&type=YESNO&to_close=3', 'description=Best js
framework&type=TEXT&to_close=10']上面写着django.utils.datastructures.MultiValueDictKeyError: 'description' '
我怎么了APIView
发布于 2019-01-22 20:36:22
首先,您需要使用create方法定义一个序列化程序,然后在视图中使用这个序列化程序类,如下所示
class QuestionSerializer(ModelSerializer):
class Meta:
model = Question
fields = ('description', 'question_type', 'answers_to_close',)
def create(self, validated_data):
Question.objects.create(description=validated_data['description'],
question_type=validated_data['question_type'],
answers_to_close=validated_data['answers_to_close'])
return validated_data
class QuestionAPIView(APIView):
serializer_class = QuestionSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data, many=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)https://stackoverflow.com/questions/54306718
复制相似问题