使用tup时ChoiceField不显示空标签

2024-06-25 23:14:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我要做的是

我会把比赛的数据保存在我的数据库里。我想能够搜索比赛的某些标准-特别是竞争类型。

关于竞争类型

竞争类型保存在一个元组中。一个略短的例子:

COMPETITION_TYPE_CHOICES = (
    (1, 'Olympic Games'),
    (2, 'ISU Championships'),
    (3, 'Grand Prix Series'),
)

它们在模型中的使用方式与so类似(同样,这是模型的简化版):

class Competition(models.Model):
    name = models.CharField(max_length=256)
    type = models.IntegerField(choices=COMPETITION_TYPE_CHOICES) 

搜索表单

我不希望搜索表单中的字段是必需的,因此表单的定义如下:

class CompetitionSearchForm(forms.Form):
    name = forms.CharField(required=False)
    type = forms.ChoiceField(choices=COMPETITION_TYPE_CHOICES,required=False)

问题

我希望ChoiceField中的select小部件显示空标签,但没有。如有任何帮助,将不胜感激:)


Tags: name模型false表单类型modelstyperequired
3条回答

我尝试了Monika和Evgeniy的解决方案,但都没有成功,但Monika有一个很好的观点,那就是选择不需要是元组。因此,最简单(也是最枯燥)的解决方案是简单地做Django在模型领域已经做的事情。只需将空白选择和元组一起转换成列表:

from django.db.models.fields import BLANK_CHOICE_DASH

...

type = forms.ChoiceField(choices=BLANK_CHOICE_DASH + list(COMPETITION_TYPE_CHOICES), required=False)

更好的选择是更新表单init方法中的字段选项

COMPETITION_TYPE_CHOICES = (
    (1, 'Olympic Games'),
    (2, 'ISU Championships'),
    (3, 'Grand Prix Series'),
)


class CompetitionSearchForm(forms.Form):
    name = forms.CharField(required=False)
    type = forms.ChoiceField(choices=COMPETITION_TYPE_CHOICES,required=False)

    def __init__(self, *args, **kwargs):
        super(CompetitionSearchForm, self).__init__(*args, **kwargs)
        self.fields['type'].choices.insert(0, ('','---------' ) )

我找到了一个解决方案,它的工作方式,我希望它不违反干燥原则。不是很干净,但我想必须这样做。

根据the documentation选择不一定是元组:

Finally, note that choices can be any iterable object -- not necessarily a list or tuple. This lets you construct choices dynamically. But if you find yourself hacking choices to be dynamic, you're probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn't change much, if ever.

所以我现在的解决办法是:

COMPETITION_TYPE_CHOICES = [
     (1, 'Olympic Games'),
     (2, 'ISU Championships'),
     (3, 'Grand Prix Series'),
]

COMP_TYPE_CHOICES_AND_EMPTY = [('','All')] + COMPETITION_TYPE_CHOICES

然后:

class CompetitionSearchForm(forms.Form):
    name = forms.CharField(required=False)
    type = forms.ChoiceField(choices=COMP_TYPE_CHOICES_AND_EMPTY, required=False)

模型保持原样。

相关问题 更多 >