yceruto/django-ajax

@ajax decorator does not set http error code in JSONResponse

reikjarloekl opened this issue · 2 comments

When raising an exception in a function decorated with @Ajax, the http status code is not set according to the error code:

HTTP status is 200 (OK):
image

However, the JSON-content is set correctly:
image

This can be fixed by changing response.py as follows (added status=data['status']):

class JSONResponse(HttpResponse):
    """
    Return a JSON serialized HTTP response
    """

    def __init__(self, data, *args, **kwargs):
        """
        This returns a object that we send as json content using
        utils.serialize_to_json, that is a wrapper to json.dumps
        method using a custom class to handle models and querysets. Put your
        options to serialize_to_json in kwargs, other options are used by
        response.
        """
        if not 'sort_keys' in kwargs:
            kwargs['sort_keys'] = settings.DEBUG

        super(JSONResponse, self).__init__(
            status=data['status'],
            content=serialize_to_json(data, *args, **kwargs),
            content_type='application/json'
        )

Result:
image

The idea is that you and the client-side application will not have to worry about capturing the ajax error. I recommend using the jQuery.ajax-plugin.min.js plugin to see the error message when it occurs.

This is a pity, because

  • it introduces a dependency between your backend- and your frontend-code that would be unnecessary otherwise because the backend works just fine with e.g. jQuery alone. People have to also use the front-end now for error handling which is just one more thing that can break if you do not need the content handling you provide in the front-end.
  • it does not follow standard HTTP logic.
  • it makes debugging harder. If I do a get_object_or_404, I expect to see a 404 code for missing objects in the browsers development tools without looking into the content of each response.
  • it prevents $(document).ajaxError() from working.
  • your front-end could still do all it's magic if the server returned the proper HTTP-code.