[Answered ]-Handling Django Model Form Error in Ajax Submit

2👍

Edited my answer. I misunderstood your question initially.

Try this:

$('.complaintform').submit(function(e){
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "/form/",
        dataType: "json",
        data: $(this).serialize(),
        success: function(data) {
            $('p').html('ok');                
        },
        statusCode: {
            400: function() {
                var items = [];
                $.each( data, function( val ) {
                items.push( val ); 
                });
                $('p').html(items.join(""));
            }
        }
    });

});

If that doesn’t work, a dirty workaround would be:

1) in the view:

else:
    data = json.dumps([v for k,v in form.errors.items()] + ['failed'])
    return HttpResponseBadRequest(data, mimetype='application/json')

2) in javascript:

success: function(data) {
    if jQuery.inArray("failed", data) {
        data.splice("failed", 1);
        var items = [];
        $.each( data, function( val ) {
            items.push( val ); 
        });
        $('p').html(items.join(""));
    } else {
        $('p').html('ok');
    }                
},

That will work if, for some strange reason, jquery thinks your HttpResponse is ‘success’.

Leave a comment