Django 尝试在窗体中显示初始值

Django 尝试在窗体中显示初始值,django,forms,python-3.x,django-forms,Django,Forms,Python 3.x,Django Forms,我试图在我的表单中显示init值(State),但它一直显示“-----”值。 我知道该值不是空的,因为它将状态保存到我的数据库中。它不会以我的形式出现 我的班级: class AddressUpdateForm(BaseModelForm): state = ProvinceModelChoiceField(required=False, queryset=CountryProvincePair.objects.all()) class Meta: model = Address

我试图在我的表单中显示init值(State),但它一直显示“-----”值。 我知道该值不是空的,因为它将状态保存到我的数据库中。它不会以我的形式出现

我的班级:

class AddressUpdateForm(BaseModelForm):
state = ProvinceModelChoiceField(required=False, queryset=CountryProvincePair.objects.all())

class Meta:
    model = Address
    fields = ('label', 'postal', 'zip', 'city', 'country', 'state', 'custombillto')

def __init__(self, *args, **kwargs):
    super(AddressUpdateForm, self).__init__(*args, **kwargs)
    print("THIS IS IT", self.instance.state)
    self.fields['state'].instance = self.instance.state
我的自定义模型选择字段:

class ProvinceModelChoiceField(ModelChoiceField):
"""
A model choice field that accepts custom values for province class.
Should be used together with Chosen with extended functionality.
This model will accept everything that is not in its Query initial values
"""

def label_from_instance(self, obj):
    return "%s, %s" % (obj.province, obj.country)

def to_python(self, value):
    if value in self.empty_values:
        return None
    try:
        key = self.to_field_name or 'pk'
        value = self.queryset.get(**{key: value})
    except (ValueError, TypeError, self.queryset.model.DoesNotExist):
        # If the object does not exist, does not raise an error
        pass
    return value
BaseModelForm:

class BaseModelForm(ModelForm):
def __init__(self, *args, **kwargs):
    super(BaseModelForm, self).__init__(*args, **kwargs)
    for label, field_instance in self.fields.items():
        if isinstance(field_instance, ModelChoiceField) or isinstance(field_instance, ChoiceField):
            field_instance.widget.attrs['class'] = 'chosen'
            field_instance.help_text = ''
        if isinstance(field_instance, BaseTemporalField):
            field_instance.widget.attrs['class'] = 'dp'
        if isinstance(field_instance, NullBooleanField):
            field_instance.widget.attrs['class'] = 'switch'
        if isinstance(field_instance, BooleanField):
            field_instance.widget.attrs['class'] = 'switch'

使用
BaseModelForm
而不是
ModelForm
的任何原因
Modelform
继承自
ModelFormMetaclass
以及
BaseModelForm
ModelFormMetaclass
中有一些字段更新逻辑,您的表单缺少该逻辑。BaseModelForm与ModelForm相同,我已将其添加到问题中。