Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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 ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda