0

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'']

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
apardes
  • 4,272
  • 7
  • 40
  • 66

1 Answers1

3

There are empty prices 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()
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • That fixed all of my errors however now whichever value is entered last is the value that is saved for all items. In the terminal my print command returns all correct values that I entered. – apardes Aug 28 '13 at 20:13
  • And `print list_item.price` returns the correct value in the terminal as well. – apardes Aug 28 '13 at 20:18
  • Not exactly, if I enter to distinct values for two distinct items they end up with the same value. – apardes Aug 28 '13 at 20:21