[Answered ]-Django JsonResponse return no data

2👍

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.

Leave a comment