简体   繁体   中英

How to get checkbox values in django application

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 empty fruit list ( [None, None] ). I don't know why it's not working, Can anybody point out the mistake. Thanks in advance

index.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'))

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. Eg:

['Apple', 'Mango']

input元素需要一个name属性,否则浏览器不会发送任何数据。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM