[Fixed]-Django forms extra empty radio button

2👍

0👍

Django has to have a way to allow None values to be set for nullable fields (fields with required=False) and does so by appending an option with an empty value. The same thing happens with Select elements.

Now, for Django to add that option to your Form the document_type field must be nullable (indeed have required=False), and I can only assume that somewhere in the definition of the Form you’re setting that option to the field.

PS: If the form is generated automatically for the Model (i.e. you’re using Django’s ModelForm) then the model should have said Field set with blank=True, null=True, yet that is clearly missing. ModelForm rocks, though, so if you’re not familiar with it, try it out.

UPDATE:

TBH I can’t work out why that’s nullable either, but try setting required=True manually in the form in the same way that @Alistair specified.

self.fields['document_type'].required = True

Right under the line where you modified that field to set the queryset. I think that should work.

0👍

A work around is to hide it with css:

#id_document_type li:first-child {display:none}

0👍

As Agustin mentioned, ModelChoiceFields must be set to required in order to remove the blank choice.

def __init__(self, queryset, empty_label="---------",
             required=True, widget=None, label=None, initial=None,
             help_text='', to_field_name=None, limit_choices_to=None,
             *args, **kwargs):
    if required and (initial is not None):
        self.empty_label = None
    else:
        self.empty_label = empty_label

Required is set to False by default, so you’ll need to add the following to your init in Document Form

self.fields['document_type'].required=True

-1👍

I solved this by adding these parameters to my declaration of my field in my model:

blank=False, default=None

So in this case, you model would look like this:

    document_type = models.ForeignKey(DocumentType,
                       verbose_name="Document Type", blank=False, default=None)

Leave a comment