Home > Software design >  Django: Why am I getting a 400 bad request error?
Django: Why am I getting a 400 bad request error?

Time:05-30

I am developing a web application on django react And I needed to make a request in which I pass a list with ids, but I have a '"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;

How can I fix this ?

CodePudding user response:

I think answers field should defined as the list of 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 }
        }

And in frontend, you need to upload with the key 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
      }
    })
}, [])
...

Then the 400 error will not occur. And of course, there are other places you need to add. Image and question field should be added in the serializer.

  • Related