2012-04-18 8 views
3

私は私のModelFormでのManyToManyFieldの選択肢をフィルタする:Django ModelFormでManyToManyFieldの選択肢をフィルタリングするにはどうすればいいですか?

class MyForm(forms.ModelForm): 
    class Meta: 
     model = Entity 
     fields = ['parent_entities'] 

    def __init__(self, *args, **kwargs): 
     self.root_entity = kwargs.pop('root_entity') 
     self.Meta.fields['parent_entities'].queryset = Entity.objects.filter(root_entity=self.root_entity) 
     super(MyForm, self).__init__(*args, **kwargs) 

私が見てきたけど、何もまだ働いていない異なる多くのコードを試してみました。

私の問題は、この 'parent_entities'フィールドを取得できないと思います。このコードでは は、私がエラーを持っている:

list indices must be integers, not str 

答えて

5
def __init__(self, *args, **kwargs): 
    # First pop your kwargs that may bother the parent __init__ method 
    self.root_entity = kwargs.pop('root_entity') 
    # Then, let the ModelForm initialize: 
    super(MyForm, self).__init__(*args, **kwargs) 
    # Finally, access the fields dict that was created by the super().__init__ call 
    self.fields['parent_entities'].queryset = Entity.objects.filter(root_entity=self.root_entity) 
+0

私はすでに前にあることを試してみましたが、私はこのエラーメッセージがあります。 はAttributeError 「MyFormを」オブジェクトが無属性「フィールド」 – user1257144

+0

権利を持っている、多分あなたがすべきを私がそうするならば、私は(理にかなって)次のエラーを持っているMyForm.fields – jpic

+0

にアクセスする前に、親__init__を呼び出します。 はTypeError __init __()予期しないキーワード引数「root_entity」を得ました。 その後、__init__を呼び出す前にkwargsからポップ...回答 – user1257144

関連する問題