我试图在表单中显示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
我的自定义ModelChoiceField:
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'