【发布时间】:2021-07-28 17:01:29
【问题描述】:
我有一个使用 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)
【问题讨论】:
标签: javascript django ajax ajaxform