1

I want to sumbit a model form with ajax and using model form validation messages:

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

In my view:

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))

But, my problem is how could I send data through HttpResponseBadRequest ? My js is:

$('.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?

        }
    });

});

1 Answer 1

2

Edited my answer. I misunderstood your question initially.

Try this:

$('.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(""));
            }
        }
    });

});


If that doesn't work, a dirty workaround would be:

1) in the view:

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

2) in 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');
    }                
},

That will work if, for some strange reason, jquery thinks your HttpResponse is 'success'.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for response alex. My form template is: {% load i18n %} {% for field in form %} <li id="{{ field.name }}" class="form-group"> <label class="col-lg-3 control-label">{{ field.label_tag }}</label> <p></p> <div class="col-lg-8"> {{ field }} </div> {% if field.errors %} <p>{{ field.errors }}</p> {% endif %} {% if field.help_text %} <p id="warning"><span class="control-label">{{ field.help_text|safe }}</span></p> {% endif %} </li> {% endfor %}
let's try then to specify the error code explicitly. please look at the updated code
jquery couldnt see the HttpBadRequest!! If form is not valid, data = json.dumps({'errors': dict([(k, [unicode(e) for e in v]) for k,v in form.errors.items()])}) . And I have to use this in success not error. Many thanks Alex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.