Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't initialise ModelForm fields on bound form?

When I try creating a ModelForm like

MyModelForm(instance=a_model_instance_)

it seems as if Django prevents any setting of initial model fields within the form's __init__ method, like:

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

    if self.instance.pk:
        if self.instance.my_field:
            my_field = self.instance.my_field
        else:
            # show parent's field instead
            my_field = self.instance.parent.my_field

        self.fields['my_field'].initial = my_field

Is there any reason why initialising a field within a form's __init__ method does not work anymore once the form is bound to an instance?

like image 739
mzu Avatar asked May 10 '26 16:05

mzu


1 Answers

I think you want to set the initial value of a field from other model field value if it is None:

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

    if self.instance.pk:
        if not self.initial.get('my_field'):
            self.initial['my_field'] = self.instance.parent.my_field
like image 126
Aamir Rind Avatar answered May 12 '26 14:05

Aamir Rind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!