解压的值太多(预期为 2)Django
Too many values to unpack (expected 2) Django
我正在创建一个包含 ChoiceField
的表单,我通过视图为其建立选择值。
根据 Django 文档 ChoiceFields Choices 选举值必须是:
Either an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field, or a callable that returns such an iterable. This argument accepts the same formats as the choices argument to a model field.
加载视图时,我没有遇到任何问题。但是,当我在验证视图中的表单后尝试获取 ChoiceField
的值时,出现错误 Too many values to unpack (expected 2)
.
我不知道我是否在 ChoiceField
中错误地添加了 choice 的值。虽然我想如果是这样的话,视图也不会加载。我做错了什么?
forms.py
class FormAffiliateReport(forms.Form):
...
referrals = forms.ChoiceField(choices=(), label='Choice Referral', widget=forms.Select(attrs={'class': 'form-control',}))
def __init__(self, referrals, *args, **kwargs):
super(FormAffiliateReport, self).__init__(*args, **kwargs)
self.fields['referrals'].choices = referrals
views.py
def affiliate_report(request):
if request.session.has_key('affiliate_code'):
affiliates = []
affiliate_code = request.session['affiliate_code']
affiliates = get_affiliates(affiliates, affiliate_code)
affiliates.sort(key=lambda affiliate: affiliate.name.title())
if request.method == 'POST':
form = FormAffiliateReport(request.POST)
if form.is_valid():
referrals = form.data['referrals']
return render(request, 'blog/affiliate_report.html', {"affiliate_code": affiliate_code, "form": form})
else:
choices = ()
for affiliate in affiliates:
choices = choices + ((str(affiliate.code), affiliate.name),)
form = FormAffiliateReport(choices)
return render(request, 'blog/affiliate_report.html', {"affiliate_code": affiliate_code, "form": form})
else:
return redirect('home')
追溯
File "C:\Users\pc\Environments\company\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "C:\Users\pc\Environments\company\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\pc\Environments\company\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\pc\Projects\company\blog\views.py", line 224, in affiliate_report
return render(request, 'blog/affiliate_report.html', {"affiliate_code": affiliate_code, "form": form})
File "C:\Users\pc\Environments\company\lib\site-packages\django\shortcuts.py", line 30, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\loader.py", line 68, in render_to_string
return template.render(context, request)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\backends\django.py", line 66, in render
return self.template.render(context)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\base.py", line 207, in render
return self._render(context)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\base.py", line 199, in _render
return self.nodelist.render(context)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\base.py", line 990, in render
bit = node.render_annotated(context)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\base.py", line 957, in render_annotated
return self.render(context)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\defaulttags.py", line 216, in render
nodelist.append(node.render_annotated(context))
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\base.py", line 957, in render_annotated
return self.render(context)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\base.py", line 1046, in render
return render_value_in_context(output, context)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\base.py", line 1024, in render_value_in_context
value = force_text(value)
File "C:\Users\pc\Environments\company\lib\site-packages\django\utils\encoding.py", line 76, in force_text
s = six.text_type(s)
File "C:\Users\pc\Environments\company\lib\site-packages\django\utils\html.py", line 385, in <lambda>
klass.__str__ = lambda self: mark_safe(klass_str(self))
File "C:\Users\pc\Environments\company\lib\site-packages\django\forms\boundfield.py", line 41, in __str__
return self.as_widget()
File "C:\Users\pc\Environments\company\lib\site-packages\django\forms\boundfield.py", line 94, in as_widget
attrs = self.build_widget_attrs(attrs, widget)
File "C:\Users\pc\Environments\company\lib\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 "C:\Users\pc\Environments\company\lib\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 "C:\Users\pc\Environments\company\lib\site-packages\django\forms\widgets.py", line 673, in _choice_has_empty_value
value, _ = choice
ValueError: too many values to unpack (expected 2)
为了使我已经在评论中提出的内容正式化:
OP 中的问题是 Form
的构造函数的 referrals
参数在将表单实例化为 form = FormAffiliateReport(request.POST)
。需要的是使用关键字参数来表示动态变化的选择。
所以,在视图中,这样做:
choices = ... # some computation, specific to the OP's needs
form = FormAffiliateReport(request.POST, choices=choices)
并在 Form
class:
def __init__(self, *args, **kwargs):
choices = kwargs.pop("choices")
super(FormAffiliateReport, self).__init__(*args, **kwargs)
self.fields['referrals'].choices = choices
我正在创建一个包含 ChoiceField
的表单,我通过视图为其建立选择值。
根据 Django 文档 ChoiceFields Choices 选举值必须是:
Either an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field, or a callable that returns such an iterable. This argument accepts the same formats as the choices argument to a model field.
加载视图时,我没有遇到任何问题。但是,当我在验证视图中的表单后尝试获取 ChoiceField
的值时,出现错误 Too many values to unpack (expected 2)
.
我不知道我是否在 ChoiceField
中错误地添加了 choice 的值。虽然我想如果是这样的话,视图也不会加载。我做错了什么?
forms.py
class FormAffiliateReport(forms.Form):
...
referrals = forms.ChoiceField(choices=(), label='Choice Referral', widget=forms.Select(attrs={'class': 'form-control',}))
def __init__(self, referrals, *args, **kwargs):
super(FormAffiliateReport, self).__init__(*args, **kwargs)
self.fields['referrals'].choices = referrals
views.py
def affiliate_report(request):
if request.session.has_key('affiliate_code'):
affiliates = []
affiliate_code = request.session['affiliate_code']
affiliates = get_affiliates(affiliates, affiliate_code)
affiliates.sort(key=lambda affiliate: affiliate.name.title())
if request.method == 'POST':
form = FormAffiliateReport(request.POST)
if form.is_valid():
referrals = form.data['referrals']
return render(request, 'blog/affiliate_report.html', {"affiliate_code": affiliate_code, "form": form})
else:
choices = ()
for affiliate in affiliates:
choices = choices + ((str(affiliate.code), affiliate.name),)
form = FormAffiliateReport(choices)
return render(request, 'blog/affiliate_report.html', {"affiliate_code": affiliate_code, "form": form})
else:
return redirect('home')
追溯
File "C:\Users\pc\Environments\company\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "C:\Users\pc\Environments\company\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\pc\Environments\company\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\pc\Projects\company\blog\views.py", line 224, in affiliate_report
return render(request, 'blog/affiliate_report.html', {"affiliate_code": affiliate_code, "form": form})
File "C:\Users\pc\Environments\company\lib\site-packages\django\shortcuts.py", line 30, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\loader.py", line 68, in render_to_string
return template.render(context, request)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\backends\django.py", line 66, in render
return self.template.render(context)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\base.py", line 207, in render
return self._render(context)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\base.py", line 199, in _render
return self.nodelist.render(context)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\base.py", line 990, in render
bit = node.render_annotated(context)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\base.py", line 957, in render_annotated
return self.render(context)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\defaulttags.py", line 216, in render
nodelist.append(node.render_annotated(context))
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\base.py", line 957, in render_annotated
return self.render(context)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\base.py", line 1046, in render
return render_value_in_context(output, context)
File "C:\Users\pc\Environments\company\lib\site-packages\django\template\base.py", line 1024, in render_value_in_context
value = force_text(value)
File "C:\Users\pc\Environments\company\lib\site-packages\django\utils\encoding.py", line 76, in force_text
s = six.text_type(s)
File "C:\Users\pc\Environments\company\lib\site-packages\django\utils\html.py", line 385, in <lambda>
klass.__str__ = lambda self: mark_safe(klass_str(self))
File "C:\Users\pc\Environments\company\lib\site-packages\django\forms\boundfield.py", line 41, in __str__
return self.as_widget()
File "C:\Users\pc\Environments\company\lib\site-packages\django\forms\boundfield.py", line 94, in as_widget
attrs = self.build_widget_attrs(attrs, widget)
File "C:\Users\pc\Environments\company\lib\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 "C:\Users\pc\Environments\company\lib\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 "C:\Users\pc\Environments\company\lib\site-packages\django\forms\widgets.py", line 673, in _choice_has_empty_value
value, _ = choice
ValueError: too many values to unpack (expected 2)
为了使我已经在评论中提出的内容正式化:
OP 中的问题是 Form
的构造函数的 referrals
参数在将表单实例化为 form = FormAffiliateReport(request.POST)
。需要的是使用关键字参数来表示动态变化的选择。
所以,在视图中,这样做:
choices = ... # some computation, specific to the OP's needs
form = FormAffiliateReport(request.POST, choices=choices)
并在 Form
class:
def __init__(self, *args, **kwargs):
choices = kwargs.pop("choices")
super(FormAffiliateReport, self).__init__(*args, **kwargs)
self.fields['referrals'].choices = choices