vmassuchetto
vmassuchetto

Reputation: 1569

Django: Initial modelform fields with the same name

I got a ModelForm with some ajax actions that create fields like:

<input type="hidden" name="myfield" value="1" />
<input type="hidden" name="myfield" value="2" />

I'm fine saving these data as ManyToMany using request.POST.getlist('myfield'), but I can't seem to initialize the hidden input fields on the update view.

What I got so far:

class MyModelForm(forms.ModelForm):
    myfield = forms.Field('Some field')

    class Meta:
        model = MyModelForm

    def __init__(self, *args, **kwargs):
        other_models = OtherModel.objects.filter(mymodelform=kwargs['instance'])

So now, how can I include each of the other_models of __init__ as hidden fields?

Upvotes: 0

Views: 166

Answers (1)

karthikr
karthikr

Reputation: 99680

You can add model forms fields dynamically in this fashion.

class MyModelForm(forms.ModelForm):
    myfield = forms.Field('Some field')

    class Meta:
        model = MyModelForm

    def __init__(self, *args, **kwargs):

        instance = kwargs.pop('instance')    
        other_models = OtherModel.objects.filter(mymodelform=instance)

        super(MyModelForm, self).__init__(*args, **kwargs)

        for i, other_model in enumerate(other_models):
            self.fields['other_model_field_{i}'.format(i=i)] = forms.CharField(widget = forms.HiddenInput(), initial=other_model.name)

Upvotes: 1

Related Questions