0

I was looking at documentation but I am maybe missing something. If I want to receive certain fields in the request's data, how can I define them? I'd like to avoid the POST or GET method to be executed if the complete fields are not in the request's data.

Example:

I need to receive (application/json):

{ "city": "Port Orange", "state": "FL", "formatted_address": "Peach Blossom Blvd 5329", "_zip": "32128" } 

But if I get only

{ "city": "Port Orange", "state": "FL", "formatted_address": "Peach Blossom Blvd 5329" } 

I'd like return a Response with an error message 400 Bad Request. But without executing the POST method. How could I do this?

PS. I am using APIView

7
  • I am able to access the JSON string in the dispatch method using request.body Commented Nov 17, 2015 at 17:10
  • Yes, but it's a string, not a dict. But I think I could give it a try. Commented Nov 17, 2015 at 17:11
  • Doing a json.loads(json_string) makes it a Python dict. Commented Nov 17, 2015 at 17:22
  • As you can see in one of my previous questions (linked before in comments) I realized that, I will give it a try and let you know. Commented Nov 17, 2015 at 17:26
  • @Gocht You can add a _zip field to your serializer. If the field is not supplied in the request, serializer will become invalid and will automatically return a 400 response. Commented Nov 17, 2015 at 17:27

1 Answer 1

0

Do something like this

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 

In your view, return the serializer errors along with the correct status code from rest_framework.status

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

8 Comments

Thanks dude, but where? I'd like to avoid the POST or GET method to be executed if the complete fields are not in the request's data
In that case you will need to override the dispatch method of the APIView which is used to call the appropriate method according to request method.
I tried that, and it's harder that I thought, please take a look at this previous questions: stackoverflow.com/questions/33745533/… and stackoverflow.com/questions/33740697/…
Why do you need to avoid the post method execution?
I really want to avoid writing validation in every view or serializer, I'd like to write something like required_fields = {'field_a', 'field_b'} in every view class (outside the GET or POST). I usually use the dispatch method to do this when working with Django, and I did it, but I have just realized that it is not a good idea with DRF
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.