Сохранение нескольких элементов в одной форме django
допустим, это вводимые пользователем данные, на мой взгляд, они хорошо подтверждены form.is_valid().
item code | description | unit | quantity
---------------------------------------------------------------
#itemInput1 | #descriptionInput1 | #unitInput1 | #quantityInput1
#itemInput2 | #descriptionInput2 | #unitInput2 | #quantityInput2
#itemInput3 | #descriptionInput3 | #unitInput3 | #quantityInput3
reqeust.POST.getlist('description') возвращает список -> ['#descriptionInput1','#descriptionInput2','#descriptionInput3']
Как я могу сохранить все ячейки, которые пользователь вводит в мою модель MaterialIndent?
так же как в myview я могу сохранить только последний элемент !!!
# models
class MaterialIndent(models.Model):
material_indent_id = models.AutoField(primary_key=True)
date_request = models.DateTimeField(auto_now_add=True)
local_code = models.CharField(max_length=10, default='Local')
quotation = models.FileField(upload_to='files/', null=True, blank=True)
description = models.CharField(max_length=200)
unit = models.CharField(max_length=100)
quantity_requested = models.DecimalField(max_digits=12, decimal_places=2)
quantity_remained = models.DecimalField(max_digits=12, decimal_places=2, null=True)
request_for = models.CharField(max_length=50)
requester = models.ForeignKey(User, on_delete=models.CASCADE)
priority = models.CharField(max_length=100)
status = models.CharField(max_length=50, default='Store Checking')
def __str__(self):
return str(self.material_indent_id)
# form
class MaterialIndentForm(ModelForm):
class Meta:
model = MaterialIndent
fields = ['local_code', 'description', 'unit', 'quantity_requested', 'request_for', 'priority','quotation']
# views
def test(request):
available_stock = SparePartsStock.objects.filter(quantity__gte=0).values_list('local_code', flat=True)
if request.method == 'POST':
form = MaterialIndentForm(request.POST, request.FILES)
if form.is_valid():
length = len(request.POST.getlist('local_code'))
post = form.save(commit=False)
for r in range(length):
local_code = request.POST.getlist('local_code')[r]
description = request.POST.getlist('description')[r]
unit = request.POST.getlist('unit')[r]
quantity_requested = request.POST.getlist('quantity_requested')[r]
post.local_code = local_code
post.description = description
post.unit = unit
post.quantity_requested = quantity_requested
post.requester = request.user
post.quantity_remained = post.quantity_requested
post.status = 'Store Checking'
post.save()
print('form is valid')
else:
print(form.errors)
else:
sparestock = SparePartsStock.objects.all()
form = MaterialIndentForm()
context = {'form': form, 'stock':available_stock, 'table': sparestock}
return render(request, 'copy.html', {})