Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter ManyToManyField choices in a Django ModelForm?

I want to filter ManyToManyField choices in my ModelForm:

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)

I tried a lot of different code I've seen but nothing has worked yet.

I guess my problem is that I can't get this 'parent_entities' field. With this code, I have the error :

list indices must be integers, not str
like image 889
user1257144 Avatar asked Apr 18 '12 09:04

user1257144


1 Answers

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)
like image 198
jpic Avatar answered Oct 20 '22 01:10

jpic