Reputation: 4380
I am trying to get data from a form, the form is reproduced a number of times based on a list. One form for each item. The form consists of a checkbox and a textfield. If the checkbox is checked then I need the accompanying textfield data as well.
view:
for item in request.POST.getlist('item_list'):
item_id = int(item)
item = Item.objects.get(id=item_id)
item_name = item.name
print item_name
list = List(name = item_name, created_on = now, edited_on = now)
for price in request.POST.getlist('price'):
print price
list_item.price = price
list_item.save()
#item.delete()
Its not shown above but now = timezone.now()
.
template:
<form action="" method="post">
{% csrf_token %}
{% for item in item_list %}
<input type="checkbox" name="item" value="{{item.id}}">{{item.name}} <input type="text" name="price"><br>
{% endfor %}
<input type="submit" value="Add Items">
</form>
This returns a validationerror [u"'' value must be a decimal number."]
. I can't figure out why it would be saying the numbers I'm inputting are not decimals. Thanks for your help.
Update:
The output when I put print request.POST.getlist('price')
is [u'2.55', u'4.32', u'23.421', u'3.00', u'', u'']
Upvotes: 0
Views: 7766
Reputation: 473813
There are empty price
s in the list, skip them. Also, cast strings to decimals:
from decimal import Decimal
...
for price in request.POST.getlist('price'):
if not price:
continue
list_item.price = Decimal(price)
list_item.save()
Upvotes: 3