5

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 :)

tunarob
  • 2,768
  • 4
  • 31
  • 48

3 Answers3

3

Update

a similar example maybe useful:

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

If you want a solution client side instead:

<script>     
$("#selectBox option[value='-----']").remove(); 
</script>
asdf_enel_hak
  • 7,474
  • 5
  • 42
  • 84
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.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
0

I ran into a similar problem but fixed it this way. First, download and install https://pypi.python.org/pypi/django-multiselectfield. If you don't know how to install, look here: django-multiselectfield can't install. Then, in 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)

In 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)

In forms.py (you can name this whatever you like):

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

This builds off the answer here: Django Model MultipleChoice

Community
  • 1
  • 1
guitarical
  • 169
  • 4
  • 14