Django, set initial data to formset with ManyToMany

前端 未结 3 671
-上瘾入骨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:21

    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.

提交回复
热议问题