11

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 ?

2
  • I'm having the same problem, only I'm building a dynamic form, adding fields inside my forms init. Commented Nov 3, 2011 at 20:06
  • Is this a ModelForm? If you are passing in an instance, the instance may be overriding the value for option. Commented Nov 12, 2013 at 21:09

3 Answers 3

12
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 ?

Sign up to request clarification or add additional context in comments.

1 Comment

No am not modifying anything with javascript. And no option = forms.BooleanField(required=False, initial=True) , doesn't work.
7

Set the attributes field:

  options = forms.MultipleChoiceField(label='some label',  choices=(('happy','Happy'),('sad','Sad')),
      widget=forms.CheckboxSelectMultiple(attrs={'checked' : 'checked'}))

Comments

4

Try:

option = forms.BooleanField(
            widget=forms.CheckboxInput(attrs={'checked': True})
        )

1 Comment

Hello and welcome to stackoverflow! Add some more details to your answer other than code. That would help others better to understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.