简体   繁体   中英

Get the values for selected multiple checkbox in Django

I am building an app with django. Now i am facing a problem with checkbox. I can retrive the values from request.POST.getlist(checkbox[]). But its comming with a list. Then i am making a for loop to use the slug to get the prices but here i faced like how to store it with a separate variable for each check box. As it is in loop, for different values with different variables is not possibe? How could i do it ?

In my model I have one table with extras. It has SSL, SECURITY, BACKUP.

If the check box of SSL and SECURITY selected then by the slug I will get the price. But i want that to add to Order model which has a fields like SSL and SECURITY .

I am getting totaly confused. How should I make the model architecture. With Hosting user can buy SSL, SECURITY, BACKUP or any of them.

def checkout(request):
    if request.method == "POST":
        extras_slugs = request.POST.getlist("checkbox[]")
        for slug in extras_slugs:

You should use request.POST.getlist here. This is example where I am storing attendance data based on checkbox.

in views:

if request.method == "POST":
            id_list = request.POST.getlist('choices')

in html

    <form  action="{% url 'submitattendance' %}" method="post" role="form">
                    {% csrf_token %}

  <table class="table table-hover">
    <thead>
      <tr>
        <th>Name</th>
        <th>Status</th>
        <th><input type="checkbox" align="center" onClick="toggle(this)"></th>
      </tr>
    </thead>
    <tbody>
    {% for attendance in attendances %}
      <tr {% if attendance.present %} style="background-color:green;"{% endif %}>
        <td>{{attendance.first_name}} {{attendance.last_name}}</td>
        <td>{{attendance.status}}</td>
        <td><input type="checkbox" name="choices" value="{{attendance.id}}" {% if attendance.present %} checked="checked"{% endif %} class="checkbox_delete"></td>
        <td><input type="hidden" name="attendances" value="{{attendance.id}}"></td>
       </tr>
    {% endfor %}
    </tbody>
  </table>

Hope this helps.

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