如何使用ajax将它们作为json循环遍历django表单错误 [英] how to loop through django form errors after getting them as json with ajax
问题描述
我的注册表单在没有错误的情况下可以正常工作,并且可以正确地保存用户,但是在通过 form.errors.as_json
My signup form works fine when there are no errors and saves users correctly but i couldn't display errors when there are form field errors after getting them with form.errors.as_json
这是表格的视图:
if request.is_ajax():
signup_form = SignupForm(request.POST)
if signup_form.is_valid():
signup_form.save()
full_name = signup_form.cleaned_data.get('full_name')
email = signup_form.cleaned_data.get('email')
raw_password = signup_form.cleaned_data.get('password1')
account = authenticate(email=email, password=raw_password)
login(request, account)
return JsonResponse({"success" : True}, status=200)
else:
return JsonResponse({'success': False},signup_form.errors.as_json() , status=400)
这是我的javascript文件中的ajax内容:
here are the ajax stuff in my javascript file:
var $signupForm = $('#form-signup');
$signupForm.submit(function (event) {
event.preventDefault();
var $signupData = $signupForm.serialize();
$.ajax({
url: "http://localhost:8000",
method: 'POST',
data: $signupData,
success: function() {
location.reload()
},
error: function () {
// display form errors in a div or console.log them
// by looping through them
},
});
});
当存在字段输入错误(例如密码太短")时,使用此代码
或类似的东西我收到错误状态代码500
和:
with this code when there are field inputs errors like "pasword is too short" or somthing like that i get error status code 500
and:
'str'对象不可调用
'str' object is not callable
在我的django服务器终端中
in my django server terminal
我对此检查了很多问题,但没有一个人提供帮助,其中大多数已经过时了
i checked many question about this but none of them helped and most of them were outdated
推荐答案
def sample(request):
form = SampleForm(request.POST)
if form.is_valid():
return JsonResponse({
'message': 'success'
})
return JsonResponse({
'errors':form.errors,
'message': 'invalid',
},
status=422
)
这篇关于如何使用ajax将它们作为json循环遍历django表单错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!