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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With