我找到了答案
How to set choices in dynamic with Django choicefield?
maersu post对我的问题投了很多票。
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
我在哪里错过了什么?
答案 0 :(得分:1)
来自doc,Choices应该是
可迭代(例如,列表或元组),其由恰好两个项目(例如[(A,B),(A,B)...])的可迭代组成,以用作该字段的选项。如果给出了这个,则默认表单小部件将是一个带有这些选项的选择框,而不是标准文本字段