简体   繁体   中英

Django JsonResponse return no data

I'm subclassing Django UpdateView to update my model using AJAX form (based on Django 1.11 and jQuery-3.2.1).

I want to change the UpdateView to return JSON data (instead of HttpResponseRedirect() or rendering form again with render_to_response())

Here's my UpdateView's subclass looks like:

class MediaSetUpdateView(UpdateView):
    def form_valid(self, form):
        self.object = form.save()
        print("Data is saved", file=sys.stderr)
        return JsonResponse({'message' : 'Data is saved'}, status=204)

    def form_invalid(self, form):
        print("form invalid", file=sys.stderr)
        return JsonResponse(form.errors.as_json(), status=422)

Here's the URL setup for my UpdateView :

urlpatterns = [
    ...,
    url(r'^mediaset/(?P<pk>[0-9]+)/$', views.MediaSetUpdateView.as_view(), name='mediaset_update'),
    ...,
]

And here's my jQuery AJAX POST:

/* The global var to store current data */
var json_storage = {"template_id":1 };

$.ajax({
    url: '/esignage/mediaset/6/',
    type: 'post', // Performing a POST request
    data : json_storage,
    dataType: 'json',         
    success: function(data) {
        console.log(data);
    },
    error: function(data) {
        console.log(data);
    }
});

The django UpdateView returns success ('Data is saved' is printed in my django console), but there's no message that is returned (console.log(data) in AJAX success() return 'undefined').

Further investigation from my browser indicates that Django didn't return any message, other than HTTP success status. Here's capture from my chrome's debugger:

HTTP/1.0 204 No Content
Date: Wed, 19 Jul 2017 09:28:09 GMT
Server: WSGIServer/0.2 CPython/3.5.2
X-Frame-Options: SAMEORIGIN
Content-Type: application/json
Content-Length: 28

Any idea how to debug the lost data from JsonResponse?

Based on Daniel Roseman, here's my code to send status/error message to AJAX form in Django view

class MediaSetUpdateView(UpdateView):
    def form_valid(self, form):
        self.object = form.save()
        #print("Data is saved", file=sys.stderr)
        return JsonResponse({'message' : 'Data is saved'}, status=200)

    def form_invalid(self, form):
        #print("form invalid", file=sys.stderr)
        return HttpResponse(form.errors.as_json(), status = 400, content_type='application/json')

Then the jQuery AJAX is:

$.ajax({
    url: ajax_url,
    type: 'put', // Performing a PUT request
    data : json_storage,
    dataType: 'json',         
    success: function(data) {
        console.log(data);
        $('#id_save_dialog_message').remove();
        $('#id_save_dialog .modal-dialog .modal-content .modal-body').prepend(
            '<div id="id_save_dialog_message" class="alert alert-success">' + data['message'] + '</div>');

    },
    error: function(data) {
        console.log(data);

        errors = $.parseJSON(data.responseText);
        error_msg = '';

        $.each(errors, function (key, data) {
            $.each(data, function (key_array, data) {
                error_msg += '<div class="row"><div class="col-md-4">'+ key + 
                            '(' + data['code'] + ')</div><div class="col-md-8">' 
                            + data['message'] + '</div></div>';
            });
        });

        $('#id_save_dialog_message').remove();
        $('#id_save_dialog .modal-dialog .modal-content .modal-body').prepend(
            '<div id="id_save_dialog_message" class="alert alert-danger">' + error_msg + '</div>');
    }
});

Note that 'jQuery.ajaxSettings.traditional = true' need to be added in order to access the success data like above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM