3

当我尝试创建一个像

MyModelForm(instance=a_model_instance_)

似乎 Django 阻止了表单__init__方法中初始模型字段的任何设置,例如:

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

一旦表单绑定到实例,是否有任何理由在表单的__init__方法中初始化字段不再起作用?

4

1 回答 1

5

我认为您想从其他模型字段值设置字段的初始值,如果它是无:

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
于 2013-01-10T15:27:53.247 回答