python - Django form replicates data -


i trying data form, form reproduced number of times based on list. 1 form each item. form consists of checkbox , textfield. if checkbox checked need accompanying textfield data well.

i asked related question here:

django validation error u"'' value must decimal number."

which solved have new issue.

view:

        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)              price in request.post.getlist('price'):                                 if not price:                                     continue                 print price                 list_item.price = decimal(price)                 list_item.save()             item.delete() 

its not shown above now = timezone.now().

template:

<form action="" method="post">      {% csrf_token %}      {% 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> 

when submit form runs through both loops twice , final prices items identical. determined inserting print functions throughout code , analyzing displayed. guess understand issue is, question how correct it, appreciated.

your template repeats following line many times:

<input type="checkbox" name="item" value="{{item.id}}">{{item.name}} <input type="text" name="price"> 

that creates form fields item , price duplicated every line. not way create form.

instead, generate lines unique values name= attributes. example,

<input type="checkbox" name="item_{{item.id}}">{{item.name}} <input type="text" name="price_{{item.id}}"> 

then in view, use loop find matching pairs:

for key, value in request.post.iteritems():     if not name.startswith('item_'):         continue     name, item_id = key.split('_')     if name == 'item':         price = request.post.get('price_%s' % item_id)         # fetch item, set price 

Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -