Django: html input type=input и checkbox
У меня проблема с отправкой данных из input type='number'
в django view.
У меня есть страница с товарами, каждый из которых имеет флажок и выбор количества (input type='number'
)
<form action="{% url 'create-order' %}" method="POST">
{% csrf_token %}
<table class="table table-responsive table-borderless">
<thead>
<th> </th>
<th>Quantity</th>
</thead>
<tbody>
{% for item in items %}
<tr class="align-middle alert border-bottom">
<td>
<input type="checkbox" id="check" name="item" value="{{ item.id }}">
</td>
<td>
<input class="input" min="1" value=1 type="number" name="quantity">
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="submitButton">
<button type="submit" class="lgbtn green">Go to order</button>
</div>
</form>
Кнопка "Отправить" переходит к просмотру:
def create_order(request):
quantities = request.POST.getlist('quantity')
items = request.POST.getlist('item')
return JsonResponse({
'quantities': quantities,
'items': items
})
Например, у меня есть 6 товаров с id = 1, 2, 3, 4, 5, 6. И если я выберу 1, 2, 3 и задам количество: 3, 4, 5, то я получу:
items = [1, 2, 3] # it's OK
quantities = [3, 4, 5, 1, 1, 1] # but I need [3, 4, 5]
В идеале, я хочу, чтобы элементы и количество были в одном объекте (Например [(1, 3), (2, 4), (3, 5)]
или dict {1: 3, 2: 4, 3: 5}
), но не обязательно, но в любом случае, мне нужно выбрать количество только для тех элементов, которые были проверены
<input class="input" min="1" value=1 type="number" name="quantity">
Этот тег гарантирует, что значение будет не меньше 1. Попробуйте
<input class="input" min="0" value=0 type="number" name="quantity">
Для следующей части вам нужно сопоставить нужный элемент с его количеством и пропустить, если количество равно 0. Вы можете сделать это с помощью чего-то вроде
def create_order(request):
#get fields from the form
quantities = request.POST.getlist('quantity')
items = request.POST.getlist('item')
#create a result array to hold pairs
result = []
#remove all the quantities that are 0
#use list comprehension as removing items while looping through array is tricky
quantities = [n for n in quantities if n != 0]
#check to make sure our item and quantities arrays are the same size
#if not user has set a quantity for a non-checked item or left checked item as 0
if len(quantities) != len(items):
#handle error
for count, item in enumerate(items):
result.append( (item, quantities[count]) )
return JsonResponse({
'result':result,
})