2011-11-11 33 views
0

我有以下型號:創建表單控件值

VARIABLE_CHOICES = (
    ('bool', 'On/Off'), 
    ('date', 'Date'), 
    ('float', 'Number'), 
    ('text', 'Text'), 
) 

class LetterVariable(models.Model): 
    name = models.CharField(max_length=20) 
    type = models.CharField(max_length=5, choices=VARIABLE_CHOICES) 
    data = models.CharField(max_length=100) 

我想創建一個表單,當我通過它從DB的LetterVariable一個實例會造成bassed爲data的corrosponding部件在type

任何想法我可能會這樣做?

回答

3
class LetterVariableForm(forms.ModelForm): 
    def __init__(self, *args, **kwargs): 
     super(LetterVariableForm, self).__init__(*args, **kwargs) 

     if not self.instance: 
      raise Exception('You forgot the instance!'); 

     if self.instance.type == 'something': 
      self.fields['data'].widget = forms.SomeWidget() 
+0

乾杯!任何機會,你可以告訴我如果一個實例沒有通過我怎麼能拋出一個錯誤? – Sevenearths

+1

查看更新,但請記住,這不是最終用戶應該看到的。您可能想要提供更好的消息或更合適的異常類型,但是您的代碼應該確保它永遠不會被提出。 –

+0

只是想提高它的發展原因 – Sevenearths