[英]Django, set initial data to formset with ManyToMany
我需要使用ManyToMany
字段將初始數據設置為formset
。
通常我在我的fomset形式中沒有 ManyToMany字段時這樣做:
PersonFormSet = forms.formsets.formset_factory(NickName, can_delete=True)
init_data = [{'name':'Vasya pupkin','nick':'Vasya'},
{'name':'Vasyapupkin','nick':'Petya'}]
nick_formset = PersonFormSet(initial=init_data)
但是現在我需要設置ManyToMany字段的初始數據並嘗試這樣的事情:
NickNameFormSet = forms.formsets.formset_factory(NickName, can_delete=True)
init_data = [{'name': 'Vasya Pupkin',
'nick': {'Vasya':'selected',
'Petya':'notselected'}}]
nick_formset = NickNameFormSet(initial=init_data)
但它不起作用。
如何將初始數據傳遞給Formset,以便像我這樣呈現我的小部件:
<select multiple="multiple" name="person_set-0-nickname" id="id_person_set-0-nickname">
<option value="1" selected="selected">Vasya</option>
<option value="2">Petya</option>
</select>
注意 :我只使用Forms和Django的Formsets。 沒有Django模型。 我實際上可以定義它,但它是空的,我正在使用NoSQL
。
您應該提供一個pk
列表作為ManyToMany關系的初始數據而不是dict
。
看看這個帖子 ,它可能會對你有所幫助。
您可以使用__init__
函數預填充初始數據。
這是我用於類似問題的內容:
class MyUpdateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyUpdateForm, self).__init__(*args, **kwargs)
self.initial['real_supplements'] = [s.pk for s in list(self.instance.plan_supplements.all())]
在我的示例中,您可以提供任何Queryset,而不是使用self.instance.plan_supplements.all()
。
像這樣:
class CustomFormSet(BaseInlineFormSet):
def __init__(self, *args, **kwargs):
kwargs['initial'] = [
{'foo_id': 1}
]
super(CustomFormSet, self).__init__(*args, **kwargs)
foo_id
取決於您為模型關系中的哪個字段選擇的值
您還必須更改表單類上的has_changed
方法,以便它知道初始值“已更改”以在保存時考慮在內:
class CustomForm(forms.ModelForm):
def has_changed(self):
"""
Overriding this, as the initial data passed to the form does not get noticed,
and so does not get saved, unless it actually changes
"""
changed_data = super(starnpc_class, self).has_changed()
return bool(self.initial or changed_data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.