Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pre-selected checkbox in django with django forms

Tags:

django

Am trying to display a pre-selected checkbox in Django :

option =  forms.BooleanField(required=False, initial=True) 

but the checkbox shows up un-checked. Am using django 1.3 beta. Am I missing something here ?

like image 765
user664004 Avatar asked Mar 17 '11 09:03

user664004


3 Answers

Try:

option = forms.BooleanField(
            widget=forms.CheckboxInput(attrs={'checked': True})
        )
like image 145
Andrés Ulloa Avatar answered Oct 03 '22 15:10

Andrés Ulloa


import django
from django import forms

class MyForm(forms.Form):
     option = forms.BooleanField(required=False, initial=True)

>>>print MyForm()
<tr><th><label for="id_option">Option:</label></th><td><input checked="checked" type="checkbox" name="option" id="id_option" /></td></tr>
>>> django.VERSION
(1, 3, 0, 'beta', 1)
>>> 

As you can see the checked="checked" is properly set.

Are you sure you are not modifying something with onload javascript ?

like image 41
Davo Avatar answered Oct 03 '22 13:10

Davo


Set the attributes field:

  options = forms.MultipleChoiceField(label='some label',  choices=(('happy','Happy'),('sad','Sad')),
      widget=forms.CheckboxSelectMultiple(attrs={'checked' : 'checked'}))
like image 45
C. Reed Avatar answered Oct 03 '22 15:10

C. Reed