4

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'))
1
  • I dont think you need to use a POST request as this normally requires a CSRF token.. use GET instead unless it is sensitive data Commented Feb 11, 2018 at 19:53

3 Answers 3

12

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']
Sign up to request clarification or add additional context in comments.

2 Comments

How to handle when the checkbox has also the checked attribute set? It seems in that case the value of fruits will be: ['on', 'on'] and there is no indication which fruits were selected.
@caram did you find solution?
1

input elements need a name attribute, otherwise the browser does not send any data.

2 Comments

But bootstrap controls have id tag instead of name
@OliviaBrown You can add the name attribute, no problem. The ids are primarily for the labels.
0

I found a solution to this problem within the post How to get POST request values in Django.

the result of request.POST.getlist('fruits') in your views

will return ['on', 'on']

To get the name of the selected fruits, target the value="name" from your input tag by using request.POST.getlist('student', '')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.