在我的模型中,我有一个char字段,如下所示:
alerting_tier = models.CharField(max_length=200, blank=True, null=True)
但是,在我的表单中,我正在提取要在此字段中使用的外部数据。到目前为止,我的尝试没有显示错误,但是也没有显示选择字段,它只是一本教科书。
class DeviceForm(forms.ModelForm):
class Meta:
model = Device
fields = ['site', 'switches', 'hostname', 'serial_no','version', 'template', 'model', 'install_date', \
'ospf_area','snmp_data','alerting_tier','host_data','solarwinds_id','smartnet','bau', \
'smartnet_contract_id','smartnet_contract_start_date','smartnet_contract_end_date','alerting_tier']
def __init__(self, *args, **kwargs):
site_id = kwargs.pop('site_id', None)
device_id = kwargs.pop('device_id', None)
self.is_add = kwargs.pop("is_add", False)
self.blank_site = kwargs.pop("blank_site", False)
super(DeviceForm, self).__init__(*args, **kwargs)
# get the alerting tiers from solarwinds
swis = solarwinds_conn()
tier_query = """
SELECT
c.Field,
c.Value,
c.DisplayName
FROM
Orion.CustomPropertyValues c
WHERE
Field = 'AlertingTier'
"""
tier_results = swis.query(tier_query)
tiers = tier_results["results"]
tier_options = []
for i in tiers:
tier_options.append(i['Value'])
self.fields['alerting_tier'].choices = tier_options
self.fields['alerting_tier'].widget.choices = tier_options
编辑:
尝试以下内容:
self.fields['alerting_tier'] = forms.Select()
self.fields['alerting_tier'].choices = tier_options
返回错误:
'Select' object has no attribute 'get_bound_field'
答案 0 :(得分:1)
您需要将小部件设置为forms.Select
,并在charfield上进行选择。一个charfield希望您默认输入文本...如您所愿。