Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a Django form with RadioSelect without getting a checked radiobutton by default?

Tags:

django

On Django 1.2.1 I'm using ModelForm and generating a form with radiobuttons:

class myModelForm(ModelForm):    
    class Meta:
        model = myModel
        widgets = {
            'choose': RadioSelect(),
        } 


This generates an extra input with bogus value:

<li><input type="radio" id="id_choose_0" value="" name="choose1" /> ---------</li>
<li><input type="radio" id="id_choose_1" value="1" name="choose1" /> First choice</li>


I understand that I can get rid of the auto-generated empty input field by setting a default:

myChoices = (
    ("1", "First choice"),("2", "Second choice"),("3", "Third choice"),
)    

class myModel(models.Model):
    choose = models.CharField(max_length=1, choices=myChoices, default=1...


So in this case the first choice is selected:

<li><input checked="checked" type="radio" id="id_choose_1" value="1" name="choose1" /> First choice</li>
<li><input type="radio" id="id_choose_2" value="2" name="choose2" /> Second choice</li>

But how do I render my form without a checked input attribute?

(and without the auto-generated one)

like image 234
amoeba Avatar asked Jul 14 '10 17:07

amoeba


2 Answers

This is kind of a hacky solution, but I've tested it to work: simply set the default for the field to a value that isn't one of the choices (I recommend setting it to None). When rendering the form, Django won't know which input to mark as checked, so it will leave all of them unchecked (without throwing an error). And the fact that there is a default means there will be no auto-generated input field.

like image 99
Aram Dulyan Avatar answered Oct 27 '22 22:10

Aram Dulyan


In Django 1.6 (didn't test it in other versions) all you need is default=None:

class myModel(models.Model):
    choose = models.CharField(..., default=None)

class myModelForm(ModelForm):
    class Meta:
        model = myModel
        widgets = {
            'choose': RadioSelect(),
        }
like image 38
allcaps Avatar answered Oct 27 '22 23:10

allcaps