tunarob
tunarob

Reputation: 3038

Django - Can't remove empty_label from TypedChoiceField

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

Upvotes: 4

Views: 2794

Answers (3)

Mithril
Mithril

Reputation: 13778

self.fields['xxx'].empty_value = None would not work If you field type is TypedChoiceField which do not have empty_label property. What should we do is to remove first choice:

class JobOpinionForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(JobOpinionForm, self).__init__(*args, **kwargs)

        for field_name in self.fields:
            field = self.fields.get(field_name)
            if field and isinstance(field , forms.TypedChoiceField):
                field.choices = field.choices[1:]

Upvotes: 4

Ben Davis
Ben Davis

Reputation: 13830

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:

include_blank = self.blank or not (self.has_default() or 'initial' in kwargs)

So, the cleanest way to avoid the empty option is to set a default on your model's field:

worker_type = models.PositiveSmallIntegerField(max_length=2, choices=TYPES_CHOICES, 
                                               default=TYPES_CHOICES[0][0])

Otherwise, you're left with manually hacking the .choices attribute of the form field in the form's __init__ method.

Upvotes: 5

Brandon Taylor
Brandon Taylor

Reputation: 34593

Try:

def __init__(self, *args, **kwargs):
    super(JobOpinionForm, self).__init__(*args, **kwargs)
    self.fields['worker_type'].empty_value = None

https://docs.djangoproject.com/en/1.3/ref/forms/fields/#typedchoicefield

Upvotes: -2

Related Questions