Django:为什么我会收到 400 错误请求错误?

Django: Why am I getting a 400 bad request error?

我正在 django + react 上开发一个 web 应用程序,我需要发出一个请求,在其中传递一个列表 有 id,但我有一个 '"POST /api/questions/ HTTP/1.1" 400 39'

models.py

class TestQuestionBlok(models.Model):
    image = models.ImageField(upload_to='questionsImages/')
    answers = models.ManyToManyField(TestAnswers)
    question = models.CharField(max_length=300)

    def __str__(self):
        return self.question

views.py

questions = []
class TestQuestionList(APIView):
    def get(self, request):
        global questions
        romms = TestQuestionBlok.objects.filter(id__in=questions)
        serializer = TestQuestionSerializers(romms, many=True)
        return Response(serializer.data)
    def post(self, request, format=None):
        global questions
        serializer1 = TestQuestionSerializers(data=request.data)
        if serializer1.is_valid():
            print(serializer1.data['answers'])
            return Response(serializer1.data, status=status.HTTP_200_OK)
        return Response(serializer1.errors, status=status.HTTP_400_BAD_REQUEST)

serializers.py

class TestQuestionSerializers(serializers.ModelSerializer):

    class Meta:
        model = TestQuestionBlok
        fields = ('answers', )

Testpage.jsx

import React, {useState, useEffect} from 'react';
import axios from "axios";
import { useParams } from "react-router-dom";
import "../styles/Testpage.css"

function Testpage() {
    axios.defaults.xsrfCookieName = 'csrftoken'
    axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"


    useEffect(() => {
        axios({
          method: 'POST',
          url: 'http://127.0.0.1:8000/api/questions/',
          data: {
            answers: [1, 3]
          }
        })
    }, [])

   return (
        <div>
            a
        </div>
    );
}

export default Testpage;

我该如何解决这个问题?

我认为 answers 字段应该定义为 id 的列表。

class TestQuestionSerializers(serializers.ModelSerializer):
    answer_ids = serializers.ListField(child = serializers.IntegerField(), write_only = True):

    class Meta:
        model = TestQuestionBlok
        fields = ('answers', )
        extra_kwargs = {
            'answers': { 'read_only': True }
        }

并且在前端,您需要使用密钥 answer_ids 上传。

...
useEffect(() => {
    axios({
      method: 'POST',
      url: 'http://127.0.0.1:8000/api/questions/',
      data: {
        answer_ids: [1, 3]  # here I changed the field name
      }
    })
}, [])
...

那么400错误就不会出现了。 当然,还有其他地方需要补充。 Imagequestion 字段应添加到序列化程序中。