ModelChoiceField: remove empty option and select default value

1.1k views Asked by At

I'm using the default form field for a models.ForeignKey field, which is a ModelChoiceField using the Select widget.

The related model in question is a Weekday, and the field was made nullable so that it didn't force a default value on hundreds of existing entries. However, in practice, our default should be Sunday, which is Weekday.objects.get(day_of_week=6).

By default the select widget for a nullable field when rendered displays the null option. How can I discard this option and have a default value instead?

If I set a initial value, that one is selected by default on a new form:

self.fields['start_weekday'].initial = Weekday.objects.get(day_of_week=6)

But the empty value is still listed. I tried overriding the widget choices:

self.fields['start_weekday'].widget.choices = [(wd.day_of_week, wd.name) for wd in Weekday.objects.all()]

However now Sunday isn't selected by default. I thought maybe I need to use the option value as the initial one but that didn't work either:

self.fields['start_weekday'].initial = Weekday.objects.get(day_of_week=6).pk

In short: how can I remove the empty option in a nullable model field and select a default instead?

1

There are 1 answers

0
Pruthvi Barot On

Provide empty_label=None in ModelChoiceField

start_weekday = ModelChoiceField(Weekday.objects.filter(day_of_week=6), empty_label=None)

OR

instead of assigning initial, you can assign empty_label also

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

OR

you can provide default value in field in models also

start_weekday = models.CharField(max_length=10,choices=[(wd.day_of_week, wd.name) for wd in Weekday.objects.all()],default=6)