How to change status of JsonResponse in Django

前端 未结 5 383
感情败类
感情败类 2021-02-03 16:35

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

response = JsonResponse({\'status         


        
5条回答
  •  春和景丽
    2021-02-03 17:20

    This answer from Sayse works but it's undocumented. If you look at the source you find that it passes the remaining **kwargs to the superclass constructor, HttpStatus. However in the docstring they don't mention that. I don't know if it's the convention to assume that keyword args will be passed to the superclass constructor.

    You can also use it like this:

    JsonResponse({"error": "not found"}, status=404)
    

    I made a wrapper:

    from django.http.response import JsonResponse
    
    class JsonResponseWithStatus(JsonResponse):
        """
        A JSON response object with the status as the second argument.
    
        JsonResponse passes remaining keyword arguments to the constructor of the superclass,
        HttpResponse. It isn't in the docstring but can be seen by looking at the Django
        source.
        """
        def __init__(self, data, status=None, encoder=DjangoJSONEncoder,
                     safe=True, json_dumps_params=None, **kwargs):
            super().__init__(data, encoder, safe, json_dumps_params, status=status, **kwargs)
    

提交回复
热议问题