BadRequest can't return JSON?
I am trying to return a JSON object along with a 400 error code.
This correctly returns the object (e.g. {"email": ["A user with that email address already exists."]}:
return HttpResponse(json.dumps(dict(form.errors.items())))
Whereas these all just returns an unreadable (by javascript) object ([object Object]):
return BadRequest(json.dumps(dict(form.errors.items())))
return HttpResponseBadRequest(json.dumps(dict(form.errors.items())))
return BadRequest(json.dumps(dict(form.errors.items())), content_type='application/json')
I've tried several other methods of sending an error code but the results were the same. How do I get the readable object along with a 400 Bad Request error code?
Probably the easiest way is a JsonResponse [Django-doc] with status=400:
def my_view(request):
# …
return JsonResponse(dict(form.errors.items()), status=400)
this also omits serializing manually.