Ajax 中未显示 Django 表单字段错误

Django form fields errors not showing in Ajax

我有一个使用 AJAX 的 Django 表单。该表格按预期工作。现在的问题是当输入无效输入时,不会显示 Django 表单错误。我遵循了 here 中描述的 Django 表单 API。有解决这个问题的可能方法吗?

main.js

$(document).ready(function(){
    $("#itemForm").on('submit', function (e) {
        e.preventDefault();
        var serializedData = $(this).serialize();
        $.ajax({
            type: 'POST',
            url: "post/ajax/myURL/",
            data: serializedData,
            success: function (data) {
                if($('input[type="checkbox"]').prop("checked") == true){
                    // some codes here
                    $("#itemsTable tbody").prepend(
                        // some codes here
                    )
                    console.log("Checkbox is checked. Modal will not be closed");
                }
                else if($('input[type="checkbox"]').prop("checked") == false){
                    // some codes here
                    console.log("Checkbox is unchecked. Modal will now be closed");
                }
            },
            error: function (jqXHR, textStatus, errorText, data) {
                for (var name in data) {
                    for (var i in data[name]) {
                        $('#ajaxErrorMessage').fadeIn().text(errorText) ;
                    }
                }
                setTimeout(function() {
                    $('#ajaxErrorMessage').fadeOut("slow");
                }, 5000 );
                console.log(data.message)
                // more console logs here
            }
        })
    });
});

views.py

def create_item(request):
    # request is sent via ajax
    if request.is_ajax and request.method == "POST":
        form = ItemForm(request.POST)
        data = {}
        if form.is_valid():
            data = form.save()
            # serialize the new item object in json
            data = serializers.serialize('json', [data, ])
            # send data to the client side
            return JsonResponse({"data": data}, status=200)
        else:
            # raise form errors if there is any
            return JsonResponse(data=form.errors.as_json(escape_html=False), safe=False, status=400)
    form = ItemForm()
    return HttpResponse(data=form.errors.as_json(escape_html=False), safe=False, status=400)

jQuery.ajax()的错误函数只接收三个参数(参考https://api.jquery.com/jquery.ajax/),即:

jqXHR jqXHR, String textStatus, String errorThrown

如果您想要从 ajax 调用返回的数据,您需要从 jqXHR:

访问它
error: function (jqXHR, textStatus, errorText) {
    let data = jqXHR.responseJSON;
    // If above line does not work, might not since you don't specify `dataType: "json"` use below line
    // let data = $.parseJSON($xhr.responseText);
    // YOUR CODE HERE
}