I have field in my model:
TYPES_CHOICES = (
(0, _(u'Worker')),
(1, _(u'Owner')),
)
worker_type = models.PositiveSmallIntegerField(max_length=2, choices=TYPES_CHOICES)
When I use it in ModelForm it has “———” empty value. It’s TypedChoiceField so it hasn’t empty_label attribute., so I can’t override it in form init method.
Is there any way to remove that “———“?
That method doesn’t work too:
def __init__(self, *args, **kwargs):
super(JobOpinionForm, self).__init__(*args, **kwargs)
if self.fields['worker_type'].choices[0][0] == '':
del self.fields['worker_type'].choices[0]
EDIT:
I managed to make it work in that way:
def __init__(self, *args, **kwargs):
super(JobOpinionForm, self).__init__(*args, **kwargs)
if self.fields['worker_type'].choices[0][0] == '':
worker_choices = self.fields['worker_type'].choices
del worker_choices[0]
self.fields['worker_type'].choices = worker_choices
The empty option for any model field with choices determined within the
.formfield()method of the model field class. If you look at the django source code for this method, the line looks like this:So, the cleanest way to avoid the empty option is to set a default on your model’s field:
Otherwise, you’re left with manually hacking the
.choicesattribute of the form field in the form’s__init__method.