How to change status of JsonResponse in Django
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)
Return an actual status
JsonResponse(status=404, data={'status':'false','message':message})
Python built-in http library has new class called HTTPStatus which is come from Python 3.5 onward. You can use it when define a status
.
from http import HTTPStatus
response = JsonResponse({'status':'false','message':message}, status=HTTPStatus.INTERNAL_SERVER_ERROR)
The value of HTTPStatus.INTERNAL_SERVER_ERROR.value
is 500
. When someone read your code it's better define someting like HTTPStatus.<STATUS_NAME>
other than define an integer value like 500
. You can view all the IANA-registered status codes from python library here.