codesaurusrex
codesaurusrex

Reputation: 125

How to instantiate a checkbox in the form constructor in Django?

Here is my code:

models.py

class CheckModel(models.Model):
    a = models.BooleanField()
    b = models.BooleanField()

forms.py

class CheckForm(forms.Form):
    CHOICES = (('a', 'A',), ('b', 'B'))
    check_form= forms.MultipleChoiceField(required=False,
                                                   choices=CHOICES,
                                                   widget=forms.CheckboxSelectMultiple,
                                                   label='')

views.py

settings = CheckModel.objects.get(pk=1)
a = settings.a
b = settings.b

if request.method == 'GET':
    form = CheckForm(initial = {'a': a, 'b': b}) # <-- doesn't check or uncheck the boxes on GET

The last code is my problem. How do I instantiate a form with checkboxes checked or unchecked from variables that I get from the database?

Upvotes: 0

Views: 216

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599788

The field is called check_form, not a or `b; those are the values of that field. So you can just do:

form = CheckForm(initial = {'check_form': ['a', 'b']})

However if you're instantiating forms with data from the database, you would be better off using a ModelForm and passing in the instance parameter on initialization.

Upvotes: 2

Related Questions