Django表单验证消息未在jquery ajax post的viewa中呈现
我已经创建了django表单,并从django视图显示在html页面中。在这个页面中,我需要发布来自jqueryajax的数据,如果数据有效,那么我的django valid将变为True并执行任务并返回json值 但若数据无效,则意味着它将不会以django错误消息(如正常表单提交)呈现到相应的htmlDjango表单验证消息未在jquery ajax post的viewa中呈现,jquery,django,Jquery,Django,我已经创建了django表单,并从django视图显示在html页面中。在这个页面中,我需要发布来自jqueryajax的数据,如果数据有效,那么我的django valid将变为True并执行任务并返回json值 但若数据无效,则意味着它将不会以django错误消息(如正常表单提交)呈现到相应的html 是否有任何方法可以使用jqueryajaxpost方法执行相应字段中显示的django验证消息(就像普通的django表单post验证一样)。请任何人提供建议,Thnaks。您必须使用rend
是否有任何方法可以使用jqueryajaxpost方法执行相应字段中显示的django验证消息(就像普通的django表单post验证一样)。请任何人提供建议,Thnaks。您必须使用render_to_字符串而不是render_to_响应来呈现表单HTML代码,然后将其设置为unicode字符串 我曾经使用BeautifulSoup HTML、XHTML和XML解析器来实现这一点,以获得如下确切形式的HTML代码:
if form.is_valid():
form.save()
html = render_to_string("template.html",
{'form':form},context_instance=RequestContext(request))
soup = BeautifulSoup(html)
html_form = soup.findAll('form')
json = simplejson.dumps({'status':True,
'html':unicode(html_form[0]),
'umessage':js_translators.NotifyMessage.data_saved}, ensure_ascii=False)
return HttpResponse(json, mimetype="application/json")
else:
html = render_to_string("template.html",
{'form':form},context_instance=RequestContext(request))
soup = BeautifulSoup(html)
html_form = soup.findAll('form')
json = simplejson.dumps({'status':False,
'html':unicode(html_form[0]),
'umessage':js_translators.NotifyMessage.data_wrong}, ensure_ascii=False)
return HttpResponse(json, mimetype="application/json")
因此,在客户端,我只需使用jQuery和Ajax获得响应,并使用以下代码重写表单代码:
$('#myform').html(response.html)代码>
有了它,我用ajax的django表单验证解决了这个问题