django forms and ajax

后端 未结 3 1933
春和景丽
春和景丽 2021-02-04 22:05

I\'m trying to create a page with two functional parts:

  • a form which the user fills and submits many times
  • a chart which updates every time the user submi
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 22:53

    Why not return JSON with validation errors when form contains invalid data? Django has a Form.errors fields which contains validation errors for each field. These field can easily be converted to JSON and used to mark your inputs invalid:

    Your view:

    def submit_form_view(request):
    
        if request.method == 'POST': # If the form has been submitted...
            form = ChartForm(request.POST) 
            if form.is_valid():    # All validation rules pass
                # Return JSON response if form was OK
                response_data = {'form_saved':True, 'data':'somedata'}    
                return HttpResponse(json.dumps(response_data), mimetype="application/json")
            else:                     # Invalid data:
                # Send what were errors
                response_data = {'form_saved': False, 'errors': form.errors}
                return HttpResponse(json.dumps(response_data), mimetype="application/json")
    
        else:
            form = ChartForm() # An unbound form
    
        return render_to_response('contact.html', {
            'form': form,
        })
    

    Javascript code:

    $.ajax({
      url: '{% url someapp.submit_form_view %}',
      success: function(data) {
          if( data.form_saved ){
    
                $('#form input').removeClass('error'); // Form submit ok -> remove error class of all fields
    
                var chart_data = data.chart_data;
                // Update the chart here   
    
          }else{
                var form_errors = data.form_errors;
    
                // Display form validation errors
                for(var fieldname in form_errors) {
    
                    var errors = form_errors[fieldname];       // Array of error strings for fieldname
    
                    $('#form input[name="'+fieldname+']').addClass('error')
    
                }
          }      
      }
    });
    

提交回复
热议问题