Django, set the initial data in formet using ManyToMany

I need to set the initial data in formsetwith a field ManyToMany.

I usually do this when there is no ManyToMany field in my fomset forms:

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)

But now I need to set the initial data of the ManyToMany field and try something like this:

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)

But that does not work.

How to pass the source data to Formset so that it displays my widgets as follows:

<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 . I use only Forms and Formsets from Django. No Django Models. I can define it, but it is empty, I use NoSQL.

+4
source share
3 answers

pk ManyToMany dict.

, .

+1

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

self.instance.plan_supplements.all() Queryset.

0

:

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

foo_id ,

has_changed has_changed 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)
0

All Articles