Remove empty level in django model form

Question:

django version : 1.3.7
python version :2.6

model.py

CHOICES = (('Hospital','Hospital'),("Doctor's office", "Doctor's office"))




place_of_first = models.CharField(max_length=100, default=None, choices=CHOICES,
                                               blank=True, null=True, verbose_name="")

form.py

class Form(ModelForm):
    def __init__(self, *args, **kwargs):
       super(Form, self).__init__(*args, **kwargs)
       self.fields['creation_date'].widget.attrs['readonly'] = True



    required_css_class = 'required'

    class Meta:
        model = MODELFORM
        widgets = {
           'place_of_first' : RadioSelect()
}

its giving empty level with radiobutton like [ radioi button “——————” ]
i want to remove this level with radio button. its non-mandatory field.

Asked By: user3269734

||

Answers:

you’re getting the dashes because you have blank=True set in your model. Try switching it to blank=False.

Here’s some info from the Django site:

Unless blank=False is set on the field along with a default then a label containing “———” will be rendered with the select box. To override this behavior, add a tuple to choices containing None; e.g. (None, ‘Your String For Display’). Alternatively, you can use an empty string instead of None where this makes sense – such as on a CharField.

Answered By: chirinosky

i did face same issue. Update your forms.py file .

 if self.fields['place_of_first'].widget.choces[0][0] == "" :
    del self.fields['place_of_first'].widget.choices[0]

i hope it will work for you !!!

Answered By: Ashish Kumar Saxena

remove ——– from select

def __init__(self, *args, **kwargs):
    super(RelatedAddForm, self).__init__(*args, **kwargs)
    status_excluded = ['','-']
    self.fields['name'].choices = [(k, v) for k, v in self.fields['name'].choices if k not in status_excluded]
Answered By: JopaBoga

To Remove ——– from Select Option

Set empty_label = None in your form field

Learn more https://docs.djangoproject.com/en/4.1/ref/forms/fields/#django.forms.ModelChoiceField.empty_label

place_of_first = models.CharField(
    max_length=100,
    default=None,
    choices=CHOICES,
    blank=True,
    null=True,
    verbose_name=""
    empty_label = None,
)
Answered By: Suraj Datheputhe
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.