0

I'm pretty new to web development so please forgive me in advance for my ignorance.

I'm using React to try to post data to server endpoint managed by Django using this method:

sendData(data) {
  const url = "http://127.0.0.1:8080/api/filtros/1/";
  const requestOptions = {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
  };
  fetch(url, requestOptions);
}

On the onClick of a NavDropdown React component:

<NavDropdown.Item
  key={item.id}
  onClick={() =>
    this.sendData({
      id: 0,
      dimension_id: dimension.id,
      item_id: item.id,
      usuario_id: 1
    })
  }
>
  {item.descripcion}
</NavDropdown.Item>

This is how I register the url on the router using Django:

router.register('api/filtros/1', FiltroUsuariosViewSet, 'filtro')

My Django ModelViewSet looks like this:

class FiltroUsuariosViewSet(viewsets.ModelViewSet):

    queryset = FiltroUsuarios.objects.all()
    permission_classes = [
        permissions.AllowAny
    ]
    serializer_class = FiltroUsuariosSerializers

And my Django Serializer looks like this:

class FiltroUsuariosSerializers (serializers.ModelSerializer):
    class Meta:
        model = FiltroUsuarios
        fields = ('id', 'dimension_id', 'item_id', 'usuario_id')

    def create(self, validated_data):
        post = FiltroUsuarios.objects.create(**validated_data)

When I click on the Component I get this: POST http://127.0.0.1:8080/api/filtros/1/ 400 (Bad Request) and apparently the error is on the fetch request.

Do you guys have any idea on whats the problem?

Thanks a lot in advance!

3
  • 3
    Open dev tools and in your network tab check what is the payload you're sending to the backend. 400 Bad Request means that the data you are sending is not a proper one. Commented Mar 23, 2020 at 16:27
  • 1
    I agree @Kox, maybe because the data you sent is not what the Django REST API's expects. Commented Mar 23, 2020 at 16:32
  • I had a similar problem with JQuery, remove headers: { Accept: "application/json", "Content-Type": "application/json" }, and try again, it worked for me, don't know why tho Commented Feb 24, 2021 at 13:29

1 Answer 1

4

The best way to understand and get rid of 400 Bad Request errors when wiring Django and React, is to run Django in development mode and then fire up your browser's Network tab while sending the request.

Switch into the Network -> Response tab and call sendData(). Since you are running on Django's development server, you will get the specific exception on your 400 Bad Request error. To simulate this, see the screenshot below and notice:

{"user": ["Incorrect type. Expected pk value, received str."]}

enter image description here

Back to your problem, you have the following in your .sendData():

x = {
      id: 0,
      dimension_id: dimension.id,
      item_id: item.id,
      usuario_id: 1
    }

Which you then call JSON.stringify() on. If dimension.id and item_id are both integer (a reasonable assumption), then you're passing the following as a payload:

JSON.stringify(x)
# returns:
"{"id":0,"dimension_id":1,"item_id":2,"usuario_id":3}"

Your Django Model for FiltroUsuarios defined these columns / fields, so you now need to check both your models and FiltroUsuariosSerializers that these are expected value / value types mapping to these columns.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.