Django, set initial data to formset with ManyToMany

*爱你&永不变心* 提交于 2019-12-03 08:26:54
Stan

You should provide a list of pk as initial data for your ManyToMany relation instead of a dict.

Take a look at this thread, it might helps you.

You can use the __init__ function to pre-populate initial data.

Here's what I used for a similar problem:

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())]

Instead of using self.instance.plan_supplements.all() in my example, you can provide any Queryset.

Like this:

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

the foo_id depends on the value that you're selecting for which field on the model relationship

You have to change also the has_changed method on the form class in order for the it to know that the initial values are "changed" to be taken in account when saved:

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!