0

My form has CheckboxSelectMultiple widget receiving user's preferences.
I want to show a pre-checked preference to user.
I know there is one way to pre-check widget in the template.
But I want to know a way to pre-check in the view individually. How can I do that?

jhonkola
  • 3,385
  • 1
  • 17
  • 32
crazy_rudy
  • 157
  • 2
  • 9

2 Answers2

2

Just pass the values you want to be checked to initial (see docs) when you instantiate the form:

MyForm(initial={
    'my_multi': ['a', 'b', 'c']
})
mVChr
  • 49,587
  • 11
  • 107
  • 104
  • What's the meaning of 'my_multi'? – crazy_rudy Mar 09 '13 at 18:39
  • @user1924839 that's the name of your CheckboxSelectMultiple widget field, and a, b, c are the values you want checked. You didn't provide any sample code so I had to make them up. – mVChr Mar 09 '13 at 18:40
0
import django
from django import forms

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

It renders so

<tr><th><label for="id_option">Option:</label></th><td><input checked="checked" type="checkbox" name="option" id="id_option" /></td></tr>
Ellochka Cannibal
  • 1,750
  • 2
  • 19
  • 31