2013-10-29 18 views
11

親フォーム/インスタンスのプロパティに基づいてインラインで選択フィールドのデフォルト値を設定しようとしています。私はGoogleで検索したが、インライン内から親フォームを参照については何も見つけることができないようDjango - 親インスタンスに基づくインラインフィールド値

def get_form(self, ***): 
    if self.parent.instance && self.parent.instance.field_x == "y": 
     self.field_name.choices = ... 

擬似コードでは、それは次のようになります。

私はこれを逆にして、親の中からインラインにアクセスしなければならないのでしょうか?

def get_form(self, ***): 
    if self.instance: 
     for inline in self.inlines: 
      if instanceof(inline, MyInline): 
      inline.field_name.choices = ... 

上記のいずれかは可能ですか?

+4

これを試しましたか? http://stackoverflow.com/questions/1824267/limit-foreign-key-choices-in-select-in-an-inline-form-in-admin – gorus

+1

私はこれを定期的に行います。 get_formの代わりに_construct_formを使用してください。 – Esteban

答えて

1

あなたは(私が思う)get_form_kwargsメソッドを使用しますので、

class Form(forms.Form): 
    def __init__(self, *args, **kwargs): 
     choices = kwargs.pop('choices', None) 
     super(Form, self).__init__(*args, **kwargs) 
     form.field.choices = choices 

class FormView(generic.FormView): 

    def get_form_kwargs(self, *args, **kwargs) 
     kwargs = super(FormView, self).get_form_kwargs() 
     kwargs['choices'] = choices 
     return kwargs 

あなたはget_form_kwargs方法であなたの親オブジェクトのチェックを行うと、別の選択肢に渡すことができますようにフォームのinitメソッドに選択肢を渡すことができ

関連する問題