2011-11-11 13 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のインスタンスを渡すとき、それはdata bassedため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

関連する問題