[英]Django dynamics ChoiceFields choices from APIs raises ValueError
我找到了關於如何通過Django choicefield動態設置選擇的答案?
maersu郵政對我的問題投了高票。
get_branch()
的輸出為["first_branch", "second_branch"]
django==1.11
python 3.6.0
forms.py
class FactoryPOSForm(forms.ModelForm):
branch_name = forms.ChoiceField(choices=['aa', 'bb'])
class Meta:
model = FactoryPOS
fields = [
'branch_name',
'dealer_name',
'shop_name',
'factory',
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['branch_name'].choices = get_branches()
錯誤:
File "/Users/el/.pyenv/versions/eneos-factory/lib/python3.6/site-packages/django/forms/boundfield.py", line 250, in build_widget_attrs
if widget.use_required_attribute(self.initial) and self.field.required and self.form.use_required_attribute:
File "/Users/el/.pyenv/versions/eneos-factory/lib/python3.6/site-packages/django/forms/widgets.py", line 690, in use_required_attribute
return use_required_attribute and first_choice is not None and self._choice_has_empty_value(first_choice)
File "/Users/el/.pyenv/versions/eneos-factory/lib/python3.6/site-packages/django/forms/widgets.py", line 673, in _choice_has_empty_value
value, _ = choice
ValueError: too many values to unpack (expected 2)
[22/Apr/2017 16:47:04] ERROR [django.server:124] "GET /admin/factories_pos/factorypos/add/ HTTP/1.1" 500 445135
我在哪里想念什么?
從文檔中,選擇應該是
本身由恰好兩個項目(例如[[(A,B),(A,B)...])的可迭代對象組成的可迭代對象(例如列表或元組),用作該字段的選擇。 如果提供了此選項,則默認表單窗口小部件將是具有這些選擇的選擇框,而不是標准文本字段
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.