2013-07-10 61 views
1

我有一個表單,我正在使用它來創建一個url來轉發用戶。我的表單叫SearchForm,它有一些BooleanFields,一些ModelChoiceFields,一些CharFields等。在我看來,我想要做的是遍歷表單中的(綁定)字段,並且如果有值字段設置爲required=False)添加到名爲search的字符串,如"FieldName=Value"。有沒有辦法通過的所有字段進行迭代,並且這樣做:從BoundField獲得價值

for item in form: 
    name=item.name 
    value=item.value 

其中名稱將不得不領域的id和值將有值的用戶輸入?

謝謝!

回答

0
for each in form: 
    id = each.auto_id 
    value = each.value() 
+0

是。我最終提出了這個問題。還需要刪除id中的前3個字符(因爲id在定義的id前面有'id_'。 –

1

對於您的任務,您應該嘗試使用表格的cleaned_data和方法def clean()

class SearchForm(forms.Form): 
    # Everything as before. 
    ... 

    def clean(self): 
     cleaned_data = super(ContactForm, self).clean() 
     # get value of the field: 
     # name_field = cleaned_data.get("name_field") 

     if conditions: 
      cleaned_data['FieldName'] = 'value' 
     # If you will want add error messages 
     # when conditions are broken uncomment next line 
     # raise forms.ValidationError("Errors!") 

     # Always return the full collection of cleaned data. 
     return cleaned_data 

它的做法必須工作。