首页 \ 问答 \ Django - CheckboxSelectMultiple没有“------”选择(Django - CheckboxSelectMultiple without “------” choice)

Django - CheckboxSelectMultiple没有“------”选择(Django - CheckboxSelectMultiple without “------” choice)

如何从渲染的选项中删除“------”? 我用我的模型形式:

widgets = {
    'event_form': forms.CheckboxSelectMultiple(),
}

在模型中我有IntegerField选择:

EVENT_FORM_CHOICES = (
    (1, _(u'aaaa')),
    (2, _(u'bbbb')),
    (3, _(cccc')),
    (4, _(u'dddd')),
    (5, _(eeee'))
)

渲染选择包含---------作为第一个可能的选择。 我怎么能摆脱它?

编辑:我发现的唯一工作方式是(在init方法中):

tmp_choices = self.fields['event_form'].choices
del tmp_choices[0]
self.fields['event_form'].choices = tmp_choices

但它不是很优雅的方式:)


How can I remove "------" from rendered choices? I use in my model form:

widgets = {
    'event_form': forms.CheckboxSelectMultiple(),
}

In model I have IntegerField with choices:

EVENT_FORM_CHOICES = (
    (1, _(u'aaaa')),
    (2, _(u'bbbb')),
    (3, _(cccc')),
    (4, _(u'dddd')),
    (5, _(eeee'))
)

rendered choices contain --------- as first possible choice. How I can get rid of it?

EDIT: The only working way i figured out is (in init method):

tmp_choices = self.fields['event_form'].choices
del tmp_choices[0]
self.fields['event_form'].choices = tmp_choices

but it's not very elegant way :)


原文:https://stackoverflow.com/questions/9500704
更新时间:2022-11-23 22:11

最满意答案

Django包含空白选项,因为该字段没有默认值。

如果在模型中设置默认值,则Django将不包含空白选项。

class MyModel(models.Model):
    event_form = models.PositiveSmallIntegerField(choices=EVENT_FORM_CHOICES, default=1)

如果您不想在模型中设置默认值,则可以在模型表单中显式声明字段和选项,或更改模型表单的__init__方法中的选项。


Django is including the blank choice because the field doesn't have a default value.

If you set a default value in your model, then Django will not include the blank choice.

class MyModel(models.Model):
    event_form = models.PositiveSmallIntegerField(choices=EVENT_FORM_CHOICES, default=1)

If you don't want to set a default value in your model, then you can explicitly declare the field and choices in the model form, or change the choices in the model form's __init__ method.

相关问答

更多