【问题标题】:django form to display a dropdown list causes typeErrordjango 表单显示下拉列表导致 typeError
【发布时间】:2013-03-24 16:15:50
【问题描述】:

在我的应用程序中,我需要用户从下拉列表中选择一个整数值。我想我会为此创建一个表单,如下所示

class CIForm(forms.Form):
    intervaloption = forms.ChoiceField(choices = [x for x in range(1,10)],label='Days taken')

但是,当我尝试在 django shell 中使用 as_p() 显示它时,它抛出了一个 TypeError

In [29]: f= CIForm()

In [30]: f
Out[30]: <__main__.CIForm object at 0xaa93eec>

In [31]: print f.as_p()

ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (41, 0))

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
...
TypeError: 'int' object is not iterable

我不知道我做错了什么......你能帮忙吗?

【问题讨论】:

    标签: django forms typeerror


    【解决方案1】:

    来自ChoiceField 文档:

    选择

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

    这样的事情应该可以工作:

    class CIForm(forms.Form):
        intervaloption = forms.ChoiceField(choices = [(str(x), str(x)) for x in range(1,10)], label='Days taken')
    

    【讨论】:

      猜你喜欢
      • 2022-01-16
      • 2021-06-14
      • 2021-10-28
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多