[英]What is ajax gets invalid form, How can i render it?
I am working with Django and Ajax.我正在使用 Django 和 Ajax。 With the help of jQuery, i successfully sent form data to server and able to validate it.
在 jQuery 的帮助下,我成功地将表单数据发送到服务器并能够对其进行验证。
Problem arrive when form is invalid, i want that, if the form is invalid, ajax get the invalid form and render it to same template with errors like all invalid forms do.当表单无效时问题出现,我希望,如果表单无效,ajax 会获取无效表单并将其呈现到相同的模板,并出现错误,就像所有无效的 forms 一样。
How Can i do it?我该怎么做?
The closest method you can do is to return Form.errors .您可以做的最接近的方法是返回Form.errors 。 For example:
例如:
def submitSample(request):
form = SampleForm(request.POST)
response_data = {}
if form.is_valid():
form.save()
response_data['result'] = 1
else:
response_data['result'] = 0
response_data['errors'] = form.errors
return HttpResponse(response_data)
The response_data['errors']
will contain a dictionary of error messages like: response_data['errors']
将包含错误消息字典,例如:
{'title':['This field is required.']}
After sending the ajax request, you can use jQuery to display the errors on the form elements.发送 ajax 请求后,您可以使用 jQuery 在表单元素上显示错误。 Note that you will have to find a way to append the error messages next to their elements.
请注意,您将必须找到一种方法来 append 其元素旁边的错误消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.