3

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?

Alasdair
  • 298,606
  • 55
  • 578
  • 516
mzu
  • 759
  • 8
  • 20

1 Answers1

5

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
Aamir Rind
  • 38,793
  • 23
  • 126
  • 164
  • Thanks - your approach seems to work! Can you please explain what's the reason behind this? E.g. why was I not able to just set the fields directly via self.fields['my_field'].initial ? – mzu Jan 10 '13 at 15:57
  • 1
    As well as setting `initial` values when you define the field, you can [dynamically set initial data](https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.initial). This dynamic initial data takes precedence. In the model form, the initial data constructed from the instance takes precedence over the field's initial data in the same way. If you want to dig into the django code, look at the `BoundField.value()` method in `django/forms/forms.py`. – Alasdair Jan 10 '13 at 16:57