【问题标题】:ValueError with python and djangopython和django的ValueError
【发布时间】:2013-08-23 02:05:41
【问题描述】:

我确信我的 django/python 代码中有一个非常简单的错误。本质上,我正在尝试(现在)简单地制作一个具有一些下拉列表和文件上传功能的 html 表单。我有以下 sn-ps 代码:

views.py:

def convert(request):
if request.POST:
    form = ConvertForm(request.POST,request.FILES)

    if form.is_valid():
        form.save()

        # Change this to some result page,                                                   
        # but for now, just see that we got the file                                         
        return HttpResponseRedirect('/convert/convert')
else:
    form = ConvertForm()

args = {}
args.update(csrf(request))
args['form']=form

return render_to_response('convert.html',args)

在convert.html中:

{% block content %}  
 <form action="/convert/convert/" method="post" enctype="multipart/form-data">{% csrf_token %}  
 <ul> 
  {{ form.as_ul }}  
 </ul> 
 <input type="submit" name="submit" value="Convert"> 
 </form>   
{% endblock %}  

在我的 forms.py 中:

from django import forms

class ConvertForm(forms.Form):
    ff_from = forms.ChoiceField(choices=('a'))
    ff_to = forms.ChoiceField(choices=('b'))
    file = forms.FileField(max_length=200)

我得到的错误如下:

/convert/convert/处的ValueError
需要超过 1 个值才能解压
请求方法:GET
Django 版本:1.5.2
异常类型:ValueError
异常值:
需要超过 1 个值才能解压

模板渲染期间出错
在模板 /path/to/templates/convert.html 中,第 16 行出错

但我不明白为什么。我是 django 的新手,但有点习惯于 python。 convert.html 中的第 16 行是具有

的行
{{ form.as_ul }} 

一段代码。

现在我只是想让表单显示在我的网站上,而不是让它做某事!

让我知道这个描述是否完整,不习惯在这里发布问题! 谢谢!

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    您对choices 的论点在ChoiceField 中不正确。

    根据the documentation

    choices

    可迭代(例如,列表或元组)的 2 元组,用作 该领域的选择。此参数接受与 模型字段的选择参数。请参阅模型字段参考 有关选择的文档以获取更多详细信息。

    在您的情况下,您只有一个元素。你至少需要:

    choices=[('a_code', 'A Pretty Display Value')]
    

    心灵:

    • 名单
    • 元组中的两个元素

    当然,只有一个选择的ChoiceField 并不是真正的选择。您可能需要考虑:

    [
        ('a_code', u'A Pretty Display Value'), 
        ('another_code', 'Another pretty display value')
    ]
    

    【讨论】:

    • 非常感谢,我已经整理好了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 2020-02-09
    • 2020-12-10
    • 1970-01-01
    • 2012-01-06
    • 2017-03-06
    相关资源
    最近更新 更多