首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django -将表单字段更改为选择字段并动态填充

Django -将表单字段更改为选择字段并动态填充
EN

Stack Overflow用户
提问于 2018-11-15 12:54:00
回答 1查看 76关注 0票数 0

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

代码语言:javascript
复制
alerting_tier = models.CharField(max_length=200, blank=True, null=True)

然而,在我的表单中,我正在提取外部数据,我希望在这个字段中使用一个选项。到目前为止,我的尝试没有显示错误,但也没有显示一个选择字段,它只是一本教科书。

代码语言:javascript
复制
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

编辑:

试了以下几点:

代码语言:javascript
复制
    self.fields['alerting_tier'] = forms.Select()
    self.fields['alerting_tier'].choices = tier_options

返回错误:

代码语言:javascript
复制
'Select' object has no attribute 'get_bound_field'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-15 12:55:02

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53319941

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档