How to get checkbox values in django application
13,014
Solution 1
As Daniel mentioned, you have to add a name
attribute to form elements, so they are submitted to the server.
index.html
<form method="post">
{% csrf_token %}
<div class="form-check">
<input class="form-check-input" type="checkbox" value="Apple" id="apple" name="fruits">
<label class="form-check-label" for="apple">Apple</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="Mango" id="mango" name="fruits">
<label class="form-check-label" for="mango">Mango</label>
</div>
<button type="submit">Submit</button>
</form>
That way, you can get a list of fruits in your view:
views.py
if request.method == 'POST':
fruits = request.POST.getlist('fruits')
The fruits
variable would be a list of check inputs. E.g.:
['Apple', 'Mango']
Solution 2
input
elements need a name
attribute, otherwise the browser does not send any data.
Author by
Olivia Brown
Updated on June 05, 2022Comments
-
Olivia Brown almost 2 years
I am trying to use a check box control in a simple
django
application. Code Logic seems to be fine, But I am getting an emptyfruit
list ([None, None]
). I don't know why it's not working, Can anybody point out the mistake. Thanks in advanceindex.html
<div class="form-check"> <input class="form-check-input" type="checkbox" value="Apple" id="apple"> <label class="form-check-label" for="apple">Apple</label> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="Mango" id="mango"> <label class="form-check-label" for="mango">Mango</label> </div>
view.py
if request.method == 'POST': fruit = [] fruit.append(request.POST.get('apple')) fruit.append(request.POST.get('mango'))
-
johnashu about 6 yearsI dont think you need to use a POST request as this normally requires a CSRF token.. use GET instead unless it is sensitive data
-
-
Olivia Brown about 6 yearsBut bootstrap controls have
id
tag instead ofname
-
WebDevBooster about 6 years@OliviaBrown You can add the name attribute, no problem. The
id
s are primarily for the labels. -
caram over 4 yearsHow to handle when the checkbox has also the
checked
attribute set? It seems in that case the value offruits
will be:['on', 'on']
and there is no indication which fruits were selected. -
cikatomo almost 2 years@caram did you find solution?