首页 文章

Django,使用ManyToMany将初始数据设置为formset

提问于
浏览
4

我需要使用 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>

Note :我'm using only Forms, and Formsets of Django. There is no Django models. I can actually define it but it'空了,我正在使用 NoSQL .

3 回答

  • 1

    您应该提供 pk 的列表作为ManyToMany关系的初始数据,而不是 dict .

    看看this thread,它可能会对你有所帮助 .

  • 0

    您可以使用 __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() .

  • 0

    像这样:

    class CustomFormSet(BaseInlineFormSet):
        def __init__(self, *args, **kwargs):
            kwargs['initial'] = [
                {'foo_id': 1}
            ]
            super(CustomFormSet, self).__init__(*args, **kwargs)
    

    foo_id 取决于您为模型关系中的哪个字段选择的值

    您还必须更改表单类上的 has_changed 方法,以使其知道保存时要考虑的初始值是"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)
    

相关问题