Django View : Pass value from checkbox to view

DJANGO


 

<input class="form-check-input" type="checkbox" value="{{zrec.id}}" name = "chkbox" id="{{zrec.id}}">

Value field should not be blank. If kept blank value is not passed to view post.

Input should be between the form tag.

 

Note : 

input on line 8 is kept outside the form. If kept in the form , when enter button is pressed form is submitted. Since this input is controlled by javascript , the is kept outside the form to prevent submit.

Only elements embedded between the form tag will be submitted to server.

Template.html

<!-- Security Table-->
<h4> Porfolio</h4>
{% include "equity/partials/portfolio_list.html" %}


<h4> Security Listing</h4>
<div class = "row">
<input class="form-control col-6" type="text" placeholder="Search" onchange="fn_search(this.value)">
&nbsp; &nbsp;
<form action="/usersetting/portfolio/addselection/save/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="hidden" id="id_zselected" name="zselected" value="">
    <button type="submit" class="btn btn-warning">Warning</button>

</div>


<br>

<div  style="overflow-y: scroll;height:15em;">
<table class="table table-sm " >
    <thead>
      <tr>
          <th></th>
        <th scope="col" style="width: 20%;">Symbol</th>
        <th scope="col" style="width: 30%;">Security</th>
        <th scope="col">Index</th>
          <th scope="col">Action</th>
      </tr>
    </thead>
    <tbody>
        {% for zrec in zdata %}
      <tr id="c{{zrec.id}}">
        <td>
            <div class="form-check">
                <input class="form-check-input" type="checkbox" value="{{zrec.id}}" name = "chkbox" id="{{zrec.id}}">
              </div>
        </td>
        <td >{{ zrec.symbol }}</td>
        <td class="zsecurity" id={{zrec.id}}>{{ zrec.security }}</td>
        <td>{{zrec.broad_mrkt_indice}}</td>
        <td> <a class="btn btn-link" href="/usersetting/security/delete/{{zrec.id}}/" role="button">Delete </a></td>
      </tr>
        {% endfor %}
        </tbody>
  </table>
</div>
</form>


 

view.py

elif request.method == 'POST' and zaction == 'addselection' :
            # note checkbox is passed only when it is under form and value cannot be blank
            list_of_input_ids=request.POST.getlist('chkbox')
            for zitem in list_of_input_ids :

                print(zitem)

zitem will return the value of the checkbox

Reference

<input type="checkbox" name="inputs" id="option{{input.id}}" value={{input.id}} />

if request.method == 'POST':
        #gives list of id of inputs 
        list_of_input_ids=request.POST.getlist('inputs')

 

            Related