Django JSON response error status

2019-03-17 12:37发布

问题:

My API is returning a JSON object on error but the status code is HTTP 200:

response = JsonResponse({'status': 'false', 'message': message})
return response

How can I change the response code to indicate an error?

回答1:

JsonResponse normally returns HTTP 200, which is the status code for 'OK'. In order to indicate an error, you can add an HTTP status code to JsonResponse as it is a subclass of HttpResponse:

response = JsonResponse({'status':'false','message':message}, status=500)


回答2:

Return an actual status

JsonResponse(status=404, data={'status':'false','message':message})


回答3:

To change status code in JsonResponse you can do this :

response = JsonResponse({'status':'false','message':message})
response.status_code = 500
return response