Django ValueError将表单发送到模板

时间:2018-01-15 11:00:38

标签: python django django-forms

我刚刚添加了另一个表单发送到我的模板,我已经开始出现此错误。它不是很具描述性,所以我无法弄清楚我做错了什么。

错误是 ValueError: too many values to unpack (expected 2)

views.py:

def new_post(request):
    if request.method == 'POST':
        form = NewPostForm(request.POST)
        election_form = ElectionSuggestionForm(request.POST, request.user)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = Candidate.objects.get(UserID=request.user, ElectionID=election_form.PostElection)
            post.save()
            return redirect('/feed/')
    else:    
        form = NewPostForm()
        election_form = ElectionSuggestionForm(request.user)
    return render(request, 'campaign/new_post.html', {
        "form": form,
        "election_form": election_form,
    })

我认为错误来自最后一行 - 字典中的"election_form"项 - 这令人困惑,因为字典中只传递了2个项目,因此与错误消息相矛盾。

以下是有问题的表单(该视图仅使用NewPostForm(),所以我没有将其包括在内。):

forms.py:

def GetAvailableElections(user):
    candidates = Candidate.objects.all().filter(UserID=user)
    choices = []
    for i in candidates:
        choices.append(i.ElectionID.Name)
    return choices

class ElectionSuggestionForm(forms.Form):

    def __init__(self, user, *args, **kwargs):
        super(ElectionSuggestionForm, self).__init__(*args, **kwargs)
        self.fields['PostElection'] = forms.ChoiceField(choices=GetAvailableElections(user))

以下是完整的错误追溯:

Traceback (most recent call last):
  File "C:\python\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\python\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\python\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\cbuch1800\Coursework\mysite\elections\views.py", line 62, in new_post
    "election_form": election_form,
  File "C:\python\lib\site-packages\django\shortcuts.py", line 30, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\python\lib\site-packages\django\template\loader.py", line 68, in render_to_string
    return template.render(context, request)
  File "C:\python\lib\site-packages\django\template\backends\django.py", line 66, in render
    return self.template.render(context)
  File "C:\python\lib\site-packages\django\template\base.py", line 207, in render
    return self._render(context)
  File "C:\python\lib\site-packages\django\template\base.py", line 199, in _render
    return self.nodelist.render(context)
  File "C:\python\lib\site-packages\django\template\base.py", line 990, in render
    bit = node.render_annotated(context)
  File "C:\python\lib\site-packages\django\template\base.py", line 957, in render_annotated
    return self.render(context)
  File "C:\python\lib\site-packages\django\template\loader_tags.py", line 177, in render
    return compiled_parent._render(context)
  File "C:\python\lib\site-packages\django\template\base.py", line 199, in _render
    return self.nodelist.render(context)
  File "C:\python\lib\site-packages\django\template\base.py", line 990, in render
    bit = node.render_annotated(context)
  File "C:\python\lib\site-packages\django\template\base.py", line 957, in render_annotated
    return self.render(context)
  File "C:\python\lib\site-packages\django\template\loader_tags.py", line 72, in render
    result = block.nodelist.render(context)
  File "C:\python\lib\site-packages\django\template\base.py", line 990, in render
    bit = node.render_annotated(context)
  File "C:\python\lib\site-packages\django\template\base.py", line 957, in render_annotated
    return self.render(context)
  File "C:\python\lib\site-packages\django\template\base.py", line 1046, in render
    return render_value_in_context(output, context)
  File "C:\python\lib\site-packages\django\template\base.py", line 1024, in render_value_in_context
    value = force_text(value)
  File "C:\python\lib\site-packages\django\utils\encoding.py", line 76, in force_text
    s = six.text_type(s)
  File "C:\python\lib\site-packages\django\utils\html.py", line 385, in <lambda>
    klass.__str__ = lambda self: mark_safe(klass_str(self))
  File "C:\python\lib\site-packages\django\forms\boundfield.py", line 41, in __str__
    return self.as_widget()
  File "C:\python\lib\site-packages\django\forms\boundfield.py", line 101, in as_widget
    attrs = self.build_widget_attrs(attrs, widget)
  File "C:\python\lib\site-packages\django\forms\boundfield.py", line 257, in build_widget_attrs
    if widget.use_required_attribute(self.initial) and self.field.required and self.form.use_required_attribute:
  File "C:\python\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:\python\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 :(得分:0)

您的ElectionSuggestionFormuser作为第一个参数。

def __init__(self, user, *args, **kwargs):

因此,您必须将user作为第一个参数传递:

election_form = ElectionSuggestionForm(request.user, request.POST)

你现在的论点错误。

too many values to unpack错误可能是因为您的GetAvailableElections方法。确保它返回一个元组列表,例如[('a', 'A'), ('b', 'B'), ('c', 'C')]。目前,它正在返回一个列表,例如['a', 'b', 'c']