Django, set initial data to formset with ManyToMany

前端 未结 3 672
-上瘾入骨i
-上瘾入骨i 2021-02-10 21:04

I need to set initial data to formset with ManyToMany field.

Usually i\'m doing like this when there is no ManyToMany field in forms o

3条回答
  •  佛祖请我去吃肉
    2021-02-10 21:10

    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)
    

提交回复
热议问题