5

如何从呈现的选择中删除“------”?我以我的模型形式使用:

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

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

4

3 回答 3

3

更新

一个类似的例子可能有用:

country = ModelChoiceField(reference_class = Country, choices= country_choices, 
required=True, empty_label=None,  widget=forms.Select)

如果您想要一个解决方案客户端:

<script>     
$("#selectBox option[value='-----']").remove(); 
</script>
于 2012-02-29T14:27:11.510 回答
1

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.

于 2012-02-29T20:42:33.790 回答
0

我遇到了类似的问题,但以这种方式修复了它。首先,下载并安装https://pypi.python.org/pypi/django-multiselectfield。如果您不知道如何安装,请看这里:django-multiselectfield can't install。然后,在models.py中:

from multiselectfield import MultiSelectField

CHOICES_FOR_ITEM_WITH_CHOICES = (
            ("choice 1", "choice 1"),
            ("choice 2", "choice 2"),
            ("choice 3", "choice 3"),
        )
class MyModel(models.Model):
        item_with_choices = MultiSelectField(max_length=MAX_LENGTH, null=True, blank=True)

在 admin.py 中:

from .forms import MyModelForm
class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm

    list_display = ('item_with_choices',)
    list_filter = ('item_with_choices',)
    search_fields = ('item_with_choices',)

admin.site.register(MyModel, MyModelAdmin)

在 forms.py 中(你可以随意命名):

from .models import MyModel

class MyModelForm(ModelForm):

    class Meta:
        model = MyModel
        fields = (
            'item_with_choices',
            )

    def clean(self):
        # do something that validates your data
        return self.cleaned_data

这建立了这里的答案:Django Model MultipleChoice

于 2015-09-30T00:38:17.597 回答