2013-08-30 48 views
2

我從生成的元數據的形式Django的形式,沒有錯誤返回False爲is_valid()

class MeasureForm(forms.Form): 
    def __init__(self,*args,**kwargs): 
     super(MeasureForm,self).__init__() 
     measure_id = kwargs['measure_id'] 
     m = Measure.objects.get(pk=measure_id); 
     if (m): 
      # add the measure identifier as a hidden field 
      self.fields["measure_id"] = forms.IntegerField(initial = m.id , widget=forms.HiddenInput()) 
      for mp in MeasureParameters.objects.filter(measure = m): 
       # get the NVL'ed copy of the parameter 
       p = mp.get_parameter_for_measure() 
       if not p.is_modifiable: 
        # the file has a constant value 
        if (p.values and p.default): # constant must have both values and default index 
         value_ = p.values[p.values.keys()[p.default-1]]; 
         self.fields[p.name] = forms.IntegerField(
          label = p.description , 
          initial = value_, 
          help_text = p.help_text) 
         self.fields[p.name].widget.attrs['readonly'] = True 
        else: 
         raise Exception("Parameter set as unmodifiable but has no value. \ 
             [measure: %s, parameter: %s, measureparameter %s]" 
             % (m.id , p.id , mp.__unicode__())) 
       elif (p.values): 
        # convert hstore dict to list of tuples for the choices to read 
        values_ = [(v, k) for k, v in p.values.iteritems()]; 
        # set default if exists , else take the first item 
        default_ = values_[p.default-1][0] if p.default else values_[0][0] 
        self.fields[p.name] = forms.ChoiceField(
         label = p.description , 
         choices = values_ , 
         initial = default_, 
         help_text = p.help_text) 
       else: 
        self.fields[p.name] = forms.IntegerField(label = p.description, help_text = p.help_text) 
       if (not p.is_visible): 
        self.fields[p.name].widget = forms.HiddenInput() 
     else: 
      raise Exception ("Could not find measure. [measure %s]" % (m.id)) 

    def clean(self): 
     return self.cleaned_data; 

這是我的看法

def index(request,measure_id = None): 

    owners = Owner.objects.all()  
    form = None 
    result = None 
    title = None; 
    msg = None; 

    # handle the form 
    if request.method == 'POST': # the form has been submitted 
     form = MeasureForm(request.POST, measure_id = request.POST.get('measure_id')) # A form bound to the POST data 
     result = -100 
     if form.is_valid(): # All validation rules pass 
      result = 100 
     msg = "%s" % repr(form.errors) # list of validation errors 
    else: 
     if (measure_id): 
      title = Measure.objects.get(pk=measure_id).name; 
      # make an unbound form 
      form = MeasureForm(measure_id = measure_id) 

    return render(request, 'calc/index.html' , 
      {'owners' : owners, 
      'form' : form , 
      'title' : title , 
      'result' : result, 
      'debug' : msg }) 

這是我的模板片段

<div class="content"> 
    {{ form.errors }} 
    {{ form.non_field_errors }} 
    {% if form %} 
     <h2>{{ title }}</h2> 
     <form action="/calc/{{m.id}}" method="post">{% csrf_token %} 
      {{ form.as_p }} 
     <input type="submit" value="Calculate" /> 
     </form> 
    {% if result %} 
     The Result is <span class="result"> {{ result }} </span> 
    {% endif %} 
</div> 

因此,我得到空牙套{}"%s" % repr(form.errors),form.errorsform.non_field_errors什麼都不返回。表單帖子和我可以看到請求中的原始數據,但我始終從is_valid()獲取錯誤。這是爲什麼 ?

編輯:當檢查表單是否綁定時,我也會得到錯誤。猜測這是問題。爲什麼在form = MeasureForm(request.POST, measure_id = request.POST.get('measure_id'))的號召後沒有綁定表單?

** django新手,謝謝。

回答

2

因爲你沒有將參數傳遞給超級調用。你應該這樣做:

super(MeasureForm,self).__init__(*args, **kwargs) 

否則表單將永遠不會被POST數據實際初始化。

在評論後編輯該問題的答案不建議從超級調用中刪除所有參數。如果你正在傳遞measure_id你只需要事先從kwargs刪除:

def __init__(self, *args, **kwargs): 
    measure_id = kwargs.pop('measure_id', None) 
    super(MeasureForm,self).__init__(*args, **kwargs) 
+0

我只是從超級constractor去除參數解決的另一個問題。請看[這個問題](http://stackoverflow.com/questions/18527397/handling-dynamic-form-submit-in-django-forms)並告訴我如何解決這個問題。 – haki

+0

看我上面的編輯。 –

相關問題