views:

306

answers:

3

how to know if checkbox is checked (True, 1) having just the {{ form.checkbox }} form-tag?

activo is True, 1 in db.

my template is:

{{ form.activo }}
RESULTS:
<input id="id_activo" type="checkbox" name="activo" checked="checked"/>

{{ form.activo.data }}
RESULTS:
False

{{ form.activo.value }}
RESULTS:
""

No 1 or True's :S

Any hint is apreciated =')

A: 

It is checked if request.POST.has_key('activo') or the {{ form.activo.data }} actually returns True when initialized with request.POST.

Your question isn't quite clear, but maybe your problem has something to do with the fact, that browsers don't put anything in the POST data for an unchecked checkbox.

This made things complicated for me when I had to differentiate between a checkbox not being displayed at all and a displayed checkbox not having been checked. Just from looking at the POST data you can't tell those two cases apart.

mbarkhau
but there is no way to know the data that brings the bounded-form ? myform = TheForm(instance=mymodel), myform comes with data populated.
panchicore
A: 

If you want a boolean condition in templates this should work:

{% if form.activo %}
--
{% else %}
---
{% endif %}
Saurabh
@Saurabh {% if form.activo %} doesnt have any sense, cuz form.activo always come in the form, and what it displays is a html code.
panchicore
A: 

Following on from your reply to mbarkhau's answer, using instance= doesn't make the form bound, it just provides default values to the form.

Here's the logic in a template:

{% if form.is_bound %}
    {% if form.initial.activo %}
         Checked.
    {% else %}
         Not checked.
    {% endif %}
{% else %}
    {% if form.activo.data %}
         Checked.
    {% else %}
         Not checked
    {% endif %}
{% endif %}

But it makes more sense to do this logic in the view and pass extra context. Something like:

context_data = {...}
if form.is_bound:
    activo = form.data.get('activo')
else:
    activo = form.initial.get('activo')
context_data['activo'] = bool(activo)
return render_to_response('your_template.html', context_data)
SmileyChris