【问题标题】:Django generic ChoiceFieldDjango 通用选择字段
【发布时间】:2018-03-07 16:34:42
【问题描述】:

我想要一个通用的选项列表。 在里面 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 个值才能解压错误

【问题讨论】:

  • 如果出现错误,则需要显示整个内容。
  • @DanielRoseman 我收到了这个错误ValueError at /alertes/sep/ need more than 1 value to unpack Request Method: GET Request URL: http://127.0.0.1:8000/alertes/sep/ Django Version: 1.11.8 Exception Type: ValueError Exception Value: need more than 1 value to unpack Exception Location: /Users/kebson/Work/venv_rule_eng/lib/python2.7/site-packages/django/forms/widgets.py in _choice_has_empty_value, line 673 Python Executable: /Users/kebson/Work/venv_rule_eng/bin/python
  • 错误是关于我上面描述的。我只想通过一个名为 devices.py 的文件生成我的选择列表中的项目,我在其中生成项目列表,并将其呈现给 forms.py。但我得到了那个错误。

标签: python django django-forms choicefield


【解决方案1】:

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

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

【讨论】:

  • 完美运行。我唯一的问题是为什么它没有创建选择列表。因为文件生成了这 2 行:` (0, ('Erics phone')), (1, ('mySensor001')),` 顺便说一句谢谢
猜你喜欢
  • 2014-08-15
  • 2010-11-19
  • 1970-01-01
  • 2023-04-08
  • 2018-12-27
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 2013-10-20
相关资源
最近更新 更多