1

我想用 ajax 和使用模型表单验证消息来汇总模型表单:

class ComplaintForm(forms.ModelForm):
  class Meta:
      model = Complaint
      fields = [
          'title','body'
      ]


  def clean_body(self):
      form_data = self.cleaned_data
      body = self.cleaned_data.get('body', False)
      if len(body) < 2:
          raise forms.ValidationError(u'Please Add Complaint')
      return body

  def clean(self):
      cd = self.cleaned_data
      return cd

在我看来:

def forms(request):
  form = ComplaintForm()
  if request.method == "POST":
      if request.is_ajax():
          form = ComplaintForm(request.POST)
          if form.is_valid():
              c = form.save(commit=False)
              c.user_ip = get_client_ip(request)
              c.user = request.user
              c.news =  news
              c.save()
              data = serializers.serialize('json', [c,])
          else:
              data = json.dumps([v for k,v in form.errors.items()])
              return HttpResponseBadRequest(data, mimetype='application/json')
          return HttpResponse(data, mimetype='application/json')

  else:
      form = ComplaintForm()

  return render_to_response('main/form.html', {'form': form},
                          context_instance=RequestContext(request))

但是,我的问题是如何通过 HttpResponseBadRequest 发送数据?我的js是:

$('.complaintform').submit(function(e){
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "/form/",
        dataType: "json",
        data: $(this).serialize(),
        success: function(data) {
            $('p').html('ok');                
        },
        error: function(data) {
           //how could i insert model form errors here?

        }
    });

});
4

1 回答 1

2

编辑了我的答案。我最初误解了你的问题。

尝试这个:

$('.complaintform').submit(function(e){
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "/form/",
        dataType: "json",
        data: $(this).serialize(),
        success: function(data) {
            $('p').html('ok');                
        },
        statusCode: {
            400: function() {
                var items = [];
                $.each( data, function( val ) {
                items.push( val ); 
                });
                $('p').html(items.join(""));
            }
        }
    });

});


如果这不起作用,一个肮脏的解决方法是:

1)在视图中:

else:
    data = json.dumps([v for k,v in form.errors.items()] + ['failed'])
    return HttpResponseBadRequest(data, mimetype='application/json')

2)在javascript中:

success: function(data) {
    if jQuery.inArray("failed", data) {
        data.splice("failed", 1);
        var items = [];
        $.each( data, function( val ) {
            items.push( val ); 
        });
        $('p').html(items.join(""));
    } else {
        $('p').html('ok');
    }                
},

如果出于某种奇怪的原因,jquery 认为您的 HttpResponse 是“成功的”,这将起作用。

于 2013-10-19T16:22:41.197 回答