Слишком много значений для распаковки (ожидается 2) Django - PullRequest
0 голосов
/ 17 февраля 2019

Я создаю форму, которая содержит ChoiceField, для которого я устанавливаю значения выбора с помощью представления.

Согласно документации Django ChoiceFields Choices значения выборов должны быть:

Либо итерация (например, список или кортеж) из 2-х кортежей для использования в качестве выбора для этого поля, либо вызов, который возвращает такую ​​итерацию.Этот аргумент принимает те же форматы, что и аргумент выбора для поля модели.

При загрузке представления у меня не возникает никаких проблем.Но когда я пытаюсь получить значение ChoiceField после проверки формы в представлении, я получаю ошибку Too many values to unpack (expected 2).

Я не знаю, ошибочно ли я добавляю значения выбора в ChoiceField.Хотя я полагаю, что если бы это было так, представление тоже не загрузилось бы.Что я делаю не так?

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')

Traceback

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)

1 Ответ

0 голосов
/ 17 февраля 2019

Чтобы формализовать то, что я уже положил в комментарии:

Проблема в ОП заключается в том, что аргумент referrals для конструктора Form принимает всю совокупность POST данные, когда форма была создана как form = FormAffiliateReport(request.POST).Необходимо было использовать аргумент ключевого слова для представления динамически изменяющихся вариантов.

Итак, в представлении сделайте это:

choices = ... # some computation, specific to the OP's needs
form = FormAffiliateReport(request.POST, choices=choices)

и в классе Form:

def __init__(self, *args, **kwargs):
    choices = kwargs.pop("choices")
    super(FormAffiliateReport, self).__init__(*args, **kwargs)
    self.fields['referrals'].choices = choices
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...