考虑这个模型:
class Address(models.Model):
line1 = models.CharField(max_length=255, db_index=True, blank=True, null=True)
city = models.CharField(max_length=255, db_index=True, blank=True, null=True)
state = models.CharField(max_length=255, db_index=True, blank=True, null=True)
postcode = UppercaseCharField(max_length=64, blank=True, db_index=True, null=True)
country = CountryField(db_index=True, blank=True, null=True)
我正在尝试使用通过 webhook 调用传入的数据填充此模型。在两种情况下,我无法填充该国家/地区:
当国家是“美国”时(这是 webhook 返回的内容,我无法控制它) - django_countries 无法识别这一点,所以我添加了一个 if 条件以在创建新的 Address 对象之前将“United States”更改为 USA但是,当国家不是美国时,例如“巴拿马”,我通过这样做将它直接填充到模型中:
country = request.POST.get('country') # returns something like "Panama"
Address.objects.create(line1=line1, city=city, state=state, country=country)
这很好用,除了当我尝试编辑地址表单时,国家字段为空白,它没有从选项中预先选择“巴拿马”。我知道country
这个地址实例的字段是一个国家对象,因为我可以做address_form.instance.country
它输出Pa
,如果我做address_form.instance.country.name
它输出Panama
。那么为什么表单中的国家字段没有预先选择正确的国家,为什么它显示为空白?
这是我的模型形式:
class NewAddressForm(ModelForm):
class Meta:
model = Address
fields = ['line1', 'city', 'state', 'postcode', 'country']
def __init__(self, *args, **kwargs):
super(NewAddressForm, self).__init__(*args, **kwargs)
这是我的模板 [此处仅显示国家/地区字段]
<div class="col-md-5">|
{% comment %}
COUNTRYCode: {{address_form.instance.country.code}} ---> Outputs Pa in case of Panama
COUNTRYName: {{address_form.instance.country.name}} ---> Outputs Panama in case of Panama
{% endcomment %}
<div class="form-group">
<label>{{address_form.country.label}}</label>
{% render_field address_form.country class="form-control m-b" name="country" id="country_dropdown"%}
</div>
</div>