Django-将Form字段更改为choices字段并动态填充



在我的模型中,我有一个如下所示的字符字段:

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'

您需要将小部件设置为forms.Select,并在charfield上进行选择。charfield要求您在默认情况下输入文本。。。正如你所料。

最新更新