How to get multiple values from a template and upd

2019-01-20 03:57发布

I'm fairly new to Django and Python. I have a inventory management website. I am trying to update multiple values in a database. User should be able to input updated stock values and it should update each item's stock value which has been submitted. Image of page

I tried "item[{{item.id}}]" to create a list but i'm not sure how to use this list or how to update multiple rows. My guess is that I need to gather all the values and keys from the template and in POST run a loop and update the relavant rows by ID.

template

<form action="" method="post">
  {% csrf_token %}

  {% for item in items %}
    <tr>
      <td>{{item.name}}</td>
      <td>{{item.description}}</td>
      <td>{{item.buyprice}}</td>
      <td>{{item.sellprice}}</td>
      <td><input type="number" value="{{item.instock}}" name="item[{{item.id}}]"></td>
    </tr>
  {% endfor %}
  <tr>
    <td><input type="submit" value="Update"></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  </tbody>
  </table>
</form>

view

def stockUpd(request):
    if request.method == 'GET':
        items = Item.objects.filter(user=request.user)
        context = {
        'items':items
        }
        return render(request,'stock/stockupd.html',context);
    #if request.method == 'POST':

1条回答
虎瘦雄心在
2楼-- · 2019-01-20 04:29

Do

<input type="number" value="{{item.instock}}" name="item_{{item.id}}">

Then

if request.method == 'POST':
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken', None)
    for i in data.items():
        obj = Item.objects.get(id=i[0].split("_")[1])
        if not str(obj.instock) == str(i[1]): #here check int or char datatype since 1 not equal "1"
            obj.instock = i[1]
            obj.save()
查看更多
登录 后发表回答