400 Bad Request with Django Rest Framework

I’m trying to create vote functionality through a REST API. If a User upvotes a topic, they can only downvote the topic if they decide to change their vote (and vice versa for downvotes) on the next request. For example, a User cannot make 5 PUT requests in a row of the same vote type. This is to prevent the skewing of votes on a single topic.

This is allowed: [‘upvote’, ‘downvote’, upvote’, ‘downvote’]
Not allowed: [‘upvote’, ‘upvote’, ‘upvote’, ‘upvote’]

Upon make a request to the APIView, it raises a ValidationError if this behavior is encountered and the APIView returns a 400 Bad Request with the response payload.

{'vote': [ErrorDetail(string='Duplicate vote not allowed', code='vote_error')]}
(Pdb) c
Bad Request: /api/v1/questions/3/
[15/May/2021 09:41:24] "PUT /api/v1/questions/3/ HTTP/1.1" 400 39

Upon trying to fetch the API endpoint with JavaScript; it’s raising this follow:
Failed to load resource: the server responded with a status of 400 (Bad Request)

But the client is still accepting the response payload. I want to use the payload to display a visual error.

I have raised this question here, but haven’t had any luck resolving this. My fetch request, APIView, and Serializer are included in there. Am I doing anything wrong in my API for the client error to be raised and not loading the resource?

First, I’d request you post your code here rather than relying upon links to other sources. By having the code here, it can be searched while on the site, and quoted when talking about specific lines of code.

I’m not entirely clear what you’re asking about here. Are you saying that the 400 is intended or is it not intentional?

If you want the server to return a 400, it seems like the issue would be on the JavaScript side. The server is responding with what you say you want returned, so it’s an issue of the JavaScript not properly catching the response and taking whatever desired action.

1 Like