2011-03-01 85 views
0

所以我一直在通過模型中使用&這些選擇增加了一個額外的字段到窗體,:雛型額外的字段

A_CHOICES = (
    ('none', 'none'), 
    # further conversion table 

class MyForm(ModelForm): 

extra_field_a = ChoiceField(choices=A_CHOICES) 

如果該字段是不是「無」,然後我想用它的價值在模型中的領域,但我不知道該如何找回它,我內MyForm嘗試:

def cleaned_extra(self): 
    if(self.cleaned_data.get('extra_field_a') != 'none'): 
     return self.extra_field_a 
    else: 
     return self.original_field 

但我得到一個NameError,「全局名稱沒有定義」?任何幫助非常感謝,

亞當

回答

1

這正是你將如何檢索它。撇開時髦的語法,NameError在哪裏? self未定義?你把這些代碼放在哪裏?

您通常會在clean_FOO方法中放置這種類型的特定於字段的代碼。 http://docs.djangoproject.com/en/dev/ref/forms/validation/#form-and-field-validation

def clean_extra_field_a(self): 
    data = self.cleaned_data.get('extra_field_a') 
    if data != 'none': 
     return data 
    return None # remember to set this field as required=False 

def save(self, *args, **kwargs): 
    # override save to do something with your extra field. 
    self.instance.myfield = self.cleaned_data.get('extra_field_a') 
    super(MyForm).save(*args, **kwargs) 

更新:保存在視圖中是沒有問題的。

mymodel = myform.save(commit=False) 
# ModelForm's will return the object being created/edited on save() 
# commit=False will prevent a database save 

mymodel.myfield = myform.cleaned_data.get('extra_field_a') 
mymodel.save() 

# note if you have an m2m, there is an extra method to call on commit=False 
+0

對不起,還在從PHP過渡到一個漫長而痛苦的過程,我在其他地方犯了一個錯誤的錯誤。並試圖保存在視圖中,而不是你剛纔指出的def。 – null 2011-03-01 12:40:14

+0

保存在視圖中不是問題,只要你記得從你的額外字段中提取數據,因爲你的'ModelForm'不知道如何處理它。讓我更新一個在視圖 – 2011-03-01 12:43:12

+0

保存的例子哇非常感謝:) – null 2011-03-01 12:46:26