【问题标题】:Django form validation message not render in viewa in jquery ajax postDjango 表单验证消息不在 jquery ajax post 的视图中呈现
【发布时间】:2011-12-07 16:09:35
【问题描述】:

我创建了 django 表单并从 django 视图中显示在 html 页面中。从页面我需要从 jquery ajax 发布数据,如果数据有效,那么我的 django 有效获取 True 并执行任务并返回 json 值。

但是如果无效数据意味着它不会像正常的表单提交一样呈现到带有 django 错误消息的相应 html。

有没有办法使用 jquery ajax post 方法在相应字段中显示 django 验证消息(就像普通的 django 表单后验证一样)。请任何人提供建议,Thnaks。

【问题讨论】:

    标签: jquery django


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      您必须使用 render_to_string 而不是 render_to_response 来渲染表单 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 表单验证解决了这个问题

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-06
        相关资源
        最近更新 更多