Django表单ChoiceField传字典报错ValueError,如何正确设置选项?
解决Django ChoiceField传入字典引发的ValueError问题
这个错误的根源很明确:Django的ChoiceField要求choices参数必须是由二元组组成的可迭代对象(格式为(实际值, 显示标签)),而你现在把字典直接放到列表里传进去,Django没法把它解包成需要的两个值,所以才会报too many values to unpack (expected 2)。
下面根据你的dicto.country_array的实际类型,给出对应的正确写法:
情况1:dicto.country_array是普通字典
比如它的结构是{'cn': '中国', 'us': '美国'}这种键值对形式,直接用字典的items()方法转换成二元组列表即可:
country = forms.ChoiceField( choices=dicto.country_array.items(), widget=forms.Select(attrs={'class':'form-control m-b', 'id':'country_sel'}) )
注意:Python 3.7+的字典是有序的,如果你用的是更早版本,或者需要自定义选项顺序,可以用
sorted()排序,比如按显示标签排序:sorted_choices = sorted(dicto.country_array.items(), key=lambda x: x[1]) country = forms.ChoiceField( choices=sorted_choices, widget=forms.Select(attrs={'class':'form-control m-b', 'id':'country_sel'}) )
情况2:dicto.country_array是字典组成的列表
如果它的结构是[{'value': 'cn', 'label': '中国'}, ...]这种,需要手动把每个字典转换成二元组:
# 用列表推导式生成符合要求的二元组列表 choices = [(item['value'], item['label']) for item in dicto.country_array] country = forms.ChoiceField( choices=choices, widget=forms.Select(attrs={'class':'form-control m-b', 'id':'country_sel'}) )
额外优化:动态更新选项(可选)
如果你的字典是动态生成的(比如从数据库获取),建议在表单的__init__方法里设置choices,避免Django缓存旧的选项:
class YourFormName(forms.Form): # 先初始化字段,不设置choices country = forms.ChoiceField(widget=forms.Select(attrs={'class':'form-control m-b', 'id':'country_sel'})) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # 在这里动态设置最新的选项 self.fields['country'].choices = list(dicto.country_array.items())
内容的提问来源于stack exchange,提问作者SayYes
相关产品推荐
相关产品推荐

