Nuno_147
Nuno_147

Reputation: 2913

Django choices non-selected field

I am trying to remove the non-selected option from a choices of a model form.

my model field is declared :

priority = models.IntegerField( choices=PRIORITIES_CHOICES )

my form code is :

class TaskForm(ModelForm):
def __init__(self, *args, **kwargs):
    super(TaskForm, self).__init__(*args, **kwargs)

    self.fields['priority'].required = True;

however, the non-selected field doesn't want to go away. (I am talking about the ------ option).

Any idea ?

Upvotes: 0

Views: 295

Answers (2)

Jeb
Jeb

Reputation: 1028

If anyone still wonders how to do this in Django 1.5+, the "Django way":

class TaskForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(TaskForm, self).__init__(*args, **kwargs)

        self.fields['priority'].empty_label = None

You can also directly add it in the field declaration (if you manually declare it in the init), next to the queryset, widget, required, etc.

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239220

Try:

class TaskForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(TaskForm, self).__init__(*args, **kwargs)

        self.fields['priority'].choices = self.fields['priority'].choices[1:]

Upvotes: 1

Related Questions