6

我想在我的 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
4

1 回答 1

7
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)
于 2012-04-18T09:40:40.213 回答