2012-08-15 34 views
0

我正在使用earle/django-bootstrap來顯示使用twitter引導樣式的表單。我希望能夠改變風格並顯示填寫表格時用戶提交的錯誤(即,如果他錯過了必填字段)如何在django-bootstrap中顯示錶單錯誤?

我在文檔中找不到如何輸出錯誤。我使用jquery.form.js提交表單,並在字典中的數組中返回錯誤,問題是,errors數組返回空,甚至在視圖中打印錯誤數組顯示爲空。

爲形式的代碼:

class SomeForm(BootstrapForm): 
    class Meta: 
     layout = (
     Fieldset("Form title:","first_field", "second_field",), 
    ) 

    first_field = forms.CharField(label=u'Some Text', max_length=50, error_messages={'required':u'The error msg',},required=True,) 
    second_field = forms.ModelChoiceField(label=Some Text', queryset=SomeClass.objects.all(), error_messages={'required':u'The error msg. ',}, required=True,) 

而且該視圖的代碼:

@login_required 
def new_case(request): 
    if request.method == 'POST': 
     form = SomeForm(request.POST) 
     if form.is_valid(): 
      new_case = form.save(request.user) 
      return HttpResponseRedirect('/casos/') 
     else: 
      response_dict = {'ok': False, 'msg': None, 'err': None,} 
      err = {} 
      caseErrors = {} 
      caseErrors.update(form.errors) 
      for field in caseErrors: 
       caseErrors[field] = [unicode(error) for error in caseErrors[field]] 
      err['caso']=caseErrors 
      response_dict['msg'] = u'The fields are not valid.' 
      response_dict['err'] = err 
      return HttpResponse(simplejson.dumps(response_dict), mimetype='application/json') 
    else: 
     form = SomeForm() 
     return render_to_response('casos/new_case.html', { 'form': form }, context_instance=RequestContext(request)) 

此外jQuery的

<script type="text/javascript" src="{{ STATIC_URL }}jquery/jquery.form.js"></script> 
<script type="text/javascript"> 

$(function() { 
    $('#agr_ncaso').ajaxForm({ 
     dataType: 'json', 
     beforeSubmit: before_submit, 
     success: success 
    }); 
}); 

function before_submit(formData, jqForm, options) { 
    $('.error').removeClass('error'); 
    $('.alert-error').remove(); 
    return true; 
} 

function success(json) { 
    if (json.ok) { 
     window.location = '/casos/'; 
    } 
    else if (json.err) {    
     $('<div class="alert alert-error"><strong>Error inform </strong></div>').insertBefore('form')  
     for (campo in json.err) { 
     $('#div_id_' + campo).addClass("error"); 
     } 
     $('.alert').fadeIn('slow'); 
    } 
    else { 
     alert(json.msg); 
    } 
} 

回答

1

形式的誤差內ERR [ 'casos'],不在犯錯。祝你有個美好的一天

+0

謝謝,我從之前的項目中複製了代碼。猜猜我改變了一些東西。 – Omaraf 2012-08-16 00:05:12

相關問題