Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove blank "---------" from RadioSelect

Tags:

python

django

I don't find a way to remove the first line from my Choices_list which is displayed like -------.

I already tried some things : blank=True, Blank=False, ... and this line is still there.

This is what I'm getting in my Django website :

enter image description here

My models.py and forms.py files look like :

# models.py
# coding: utf-8

from django.db import models
from django.utils.encoding import force_text

FAVORITE_THEME = (
    ('Datasystems', 'Datasystems'),
    ('Cameroun', 'Cameroun'),
)

class Theme(models.Model):
    favorite_theme = models.CharField(max_length = 20, choices=FAVORITE_THEME, verbose_name="Sélectionner le thème")



# forms.py
#-*- coding: utf-8 -*-

from django import forms
from django.forms import ModelForm
from .models import Theme

class ThemeForm(forms.ModelForm):
    class Meta:
        model = Theme
        widgets = {'favorite_theme' : forms.RadioSelect,}
        fields=('favorite_theme',)

Do you have an idea to delete or hide this line ?

Thank you

like image 975
Essex Avatar asked Feb 22 '17 11:02

Essex


2 Answers

From Django ModelForm docs:

If the model field has choices set, then the form field’s widget will be set to Select, with choices coming from the model field’s choices. The choices will normally include the blank choice which is selected by default. If the field is required, this forces the user to make a selection. The blank choice will not be included if the model field has blank=False and an explicit default value (the default value will be initially selected instead).

So to exclude blank choice in the form, both blank=False and default must be provided. Only setting blank=False will not work.

like image 197
narendra-choudhary Avatar answered Nov 11 '22 19:11

narendra-choudhary


This is an old question, but in case other users find this through Google: you need to add , blank=False, default='Unspecified' to your field.

Like this:

favorite_theme = models.CharField(max_length = 20, choices=FAVORITE_THEME, verbose_name="Sélectionner le thème", blank=False, default='Unspecified')
like image 4
Christian Avatar answered Nov 11 '22 18:11

Christian