0

我试图以 HTML 输入的形式显示所有创建的部门,并获取用户输入(value1,vlaue2)并根据“DepartmentID”更新部门表。问题是它只从循环中获取第一个值如何从 for 循环中获取所有输入。

模板

部门模板

 <input type="submit" value="Submit" >

{% for department in departments %}

<div class="row">
  <div class="col-sm-3">
  <label>value1</label>
    <input name="value1" class="form-control" />
  </div>
</div>

<br />

<div class="row">
  <div class="col-sm-3">
  <label>value2</label>
    <input name="value2" class="form-control" />
  </div>
</div>

{% endfor %}

视图.py

def department(request):
departments = Department.objects.all()
value1 = request.POST.getlist('BUID')
value2 = request.POST.getlist('GBUID')
for department in departments:
    print(value1)
    print(value2)

context = {'departments': departments}
return render(request, 'employee/department.html', context)


------------------------------------------------------------------
Output:

['1']
['2']
['1']
['2']
------------------------------------------------------------------

------------------------------------------------------------------
What I want:

['1']
['2']      and update DepartmentID that equals to 123 with value1 = 1 value2 = 2

['3']
['4']     update DepartmentID that equals to 43534 with value1 = 3 value2 = 4
------------------------------------------------------------------
4

1 回答 1

1

What you need is a model formset which will generate a set of model forms, one for each instance in the queryset you specify. Based on the above the model is Department and the default queryset will be the one you want, Department.objects.all()

You should read the documentation for model forms and for formsets first, if you aren't familiar with these concepts.

于 2021-11-10T13:10:04.717 回答