Filipe Ferminiano
Filipe Ferminiano

Reputation: 8791

Get labels from check boxes in form

I have a form that has some fields: a textarea, a text box and stochastic number of checkbox that varies depending on the product. I want to know how I can get the label of the check boxes that are checked.

This is my form:

<form class="form-inline">
<strong><h3>Revise este produto</h3></strong><br>

{% for tag in tags %}
<label class="checkbox">
<input type="checkbox" value=""> #Ótimo
</label>
{% endfor %}

<br/>
<p>&nbsp;</p>
<label>Envie outras hashtags</label> <br/>
<input type="text" class="span3" placeholder="exemplo1, exemplo2">
<br />
<p>&nbsp;</p>
<label>Deixe sua opinião (opcional)</label> <br/>
<textarea name="Text1" cols="80" class="span3" rows="5" placeholder="Digite sua opinião aqui"></textarea>
<br/>
<p>&nbsp;</p>
<button class="btn btn-primary" type="submit"><h4>Pronto!</h4></button>
</form>

Upvotes: 0

Views: 111

Answers (2)

dhana
dhana

Reputation: 6525

In models.py:

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

In the template:

{% for tag in tags %}
<label class="checkbox">
<input type="checkbox" name="tag[]" value="" {% if tag.published %}checked{% endif %}> #Ótimo
</label>
{% endfor %}

Upvotes: 1

newTag
newTag

Reputation: 2169

  • Assuming you are sending the form as a POST, the values of the selected checkboxes are in request.POST.getlist('tag').

    Note that only checked boxes are ever sent in the POST, but the list contains the value elements of all the boxes that are checked.

For example :

<input type="checkbox" name="tag[]" value="1" />
<input type="checkbox" name="tag[]" value="2" />
<input type="checkbox" name="tag[]" value="3" />
<input type="checkbox" name="tag[]" value="4" />

Say if 1,4 were checked,

check_values = request.POST.getlist('checks')

check_values will contain [1,4] (those values that were checked)

Upvotes: 1

Related Questions