Django通用ChoiceField

时间:2018-03-07 16:34:43

标签: python django django-forms choicefield

我想在表单中选择一个通用列表。 在里面 devices.py

def get_devices():
    api_url = api_url_base
    response = requests.get(api_url,headers=headers)
    if response.status_code == 200:
        return json.loads(response.content.decode('utf-8'))
    else:
        return None

#######################################
devices_infos = get_devices()

if devices_infos is not None:
    print('Voici les devices: ')
    for each in devices_infos['data']:
        device_name =  (each['name'])
        for k in range(len(devices_infos['data'])):
            mes_choix = ("(%s, ('%s'))," % (k,device_name ))

else:
    print("[!] Request failed")

它返回了我的2个设备

(0, ('Erics phone')),
(1, ('mySensor001')),

forms.py

from django import forms
from alertes.devices import *
class NameForm(forms.Form):
    nom_alerte = forms.CharField(label='Nom Alerte', max_length=100)
    devices = forms.ChoiceField(label='Liste devices', choices=mes_choix, required=False)
    user_mail = forms.EmailField(label = 'Email a envoyer', max_length=100)

在这里,我将在设备标签中有一个选择列表,如

Erics phone
mySensor001

但我得到需要超过1个值来解压错误

1 个答案:

答案 0 :(得分:1)

你根本没有创建选择列表;您只需定义一个字符串mes_choix,其中包含单个选项说明。相反,你需要一个列表或元组的选择,每个条目包含一个元组(id,name)。

if devices_infos is not None:
    mes_choix = [(i, device['name']) for i, device in enumerate(devices_infos['data'])]