Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django form: how to check out checkbox state in template

I have a form with checkboxes that works fine, but when the user submits the form with errors and my checkbox is checked I need to change div class which holds the checkbox. So I was experimenting with {{ form.mycheckbox.data }} in the template and it says False on page load. Now when user is click on a checkbox and the form has errors, it says on. So I tried:

{{ if form.mycheckbox.data == True }} doesn't work

{{ if form.mycheckbox.data != False }} doesn't work

{{ if form.mycheckbox.data == 'on' }} doesn't work

{{ if form.mycheckbox.data == on }} doesn't work

like image 952
Goran Avatar asked Sep 06 '11 21:09

Goran


2 Answers

Use {% if form.mycheckbox.value %}. This will evaluate to true if the box is checked. For the opposite behavior, use {% if not form.mycheckbox.value %}.

Note the syntax is {% if ... %}, not {{ if ...}}. Percent-brackets are for commands, double-brackets are for outputting variables.

like image 88
user931920 Avatar answered Sep 25 '22 00:09

user931920


In models.py:

class Article:
    published = BooleanField()
    (...)

In the template:

 <input type="checkbox" name="published" {% if article.published %}checked{% endif %} />
like image 44
hermansc Avatar answered Sep 27 '22 00:09

hermansc