[英]How do I filter ManyToManyField choices in a Django ModelForm?
I want to filter ManyToManyField choices in my ModelForm: 我想在我的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)
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. 我想我的问题是我无法获得这个'parent_entities'字段。 With this code, I have the error :
使用此代码,我有错误:
list indices must be integers, not str
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.