[Answer]-Django: Initial modelform fields with the same name

1👍

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)

Leave a comment