2012-04-18 1 views
3

나는 나의 ModelForm에 ManyToManyField 선택을 필터링 할 :어떻게 장고 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

은 이미 그 전에 시도를하지만 난이 오류 메시지가 : 'MyForm을'객체가 더 속성 '필드' – user1257144

+0

오른쪽이 AttributeError, 어쩌면 당신이해야을 형식 오류 __init의 __() 예기치 않은 키워드 인수 'root_entity'을 가지고 : 나는 이렇게하면 MyForm.fields – jpic

+0

에 액세스하기 전에 부모 __init__ 전화, 나는 다음과 같은 오류가 발생합니다 (어떤 의미)이있다. 는 – user1257144