Django非常奇怪地生成了表单的下拉列表

时间:2015-08-13 13:40:09

标签: django django-forms django-admin

我有这个下拉选项,它的选择基于一个枚举,表单是在管理员上生成的,但是其中两个选项有一个奇怪的值,并用括号括起来,我一直在使用这样的下拉菜单&#39这是第一次发生这种情况,不知道为什么会这样吗?谢谢

我的枚举:

window.test();

在我的模型中:

class ProjectPublicState(object):
    OPEN_FOR_APPLICATIONS = 1
    IN_PROGRESS = 2
    CLOSED = 3,
    NOT_PUBLIC = 4,

    @classmethod
    def default(cls):
        return cls.OPEN_FOR_APPLICATIONS 

和(将其更改为models.IntegerField也没有修复它)

PUBLIC_STATE_CHOICES = (
        (ProjectPublicState.OPEN_FOR_APPLICATIONS, _('Open for Applications')),
        (ProjectPublicState.IN_PROGRESS, _('In Progress')),
        (ProjectPublicState.CLOSED, _('Closed')),
        (ProjectPublicState.NOT_PUBLIC, _('Not Public')),
    )

结果:

 state_public = FSMIntegerField(
        _('Public State'),
        choices=PUBLIC_STATE_CHOICES,
        default=ProjectPublicState.default()
    )

1 个答案:

答案 0 :(得分:3)

这是因为您通过在末尾添加逗号意外地将变量CLOSEDNOT_PUBLIC转换为tuples

根据tuples:

上的Python文档
  

元组由许多以逗号分隔的值组成。

你应该删除最后的逗号,它应该可以正常工作。

class ProjectPublicState(object):
    OPEN_FOR_APPLICATIONS = 1
    IN_PROGRESS = 2
    CLOSED = 3 # remove the trailing comma
    NOT_PUBLIC = 4 # remove the trailing comma

    @classmethod
    def default(cls):
        return cls.OPEN_FOR_APPLICATIONS 

例如:

In [1]: foo = 1, # assign 'foo' as 1 with a trailing comma at the end

In [2]: foo # print foo
Out[2]: (1,) # a tuple and not just a number 

In [3]: foo = 1,2,3 # Now assign multiple values separated by commas

In [4]: foo
Out[4]: (1, 2, 3) # tuple of 3 elements