如何在 django 中提交一次将多行输入到 django 数据库中



我有一个 for 循环,每个循环都有隐藏的输入。我尝试将其输入到事务数据库中:

Models.py
class TransDetail(models.Model):
name = models.CharField(max_length=200)
price = models.DecimalField(max_digits=15,decimal_places=2)
amount = models.IntegerField()
sumprice = models.DecimalField(max_digits=15,decimal_places=2)
no_note = models.CharField(max_length=200)

class Transaction(models.Model):
no_nota = models.CharField(max_length=200)
total_nota = models.DecimalField(max_digits=15,decimal_places=2)
tanggal = models.CharField(max_length=200)

HTML Template
<table>
<tbody>
<form method="POST" action="{% url 'transactionadd' %}">
{% csrf_token %}
{% for name,amount,price,sumprice in x %}
<tr>
<td>{{name}}
<input type="hidden" name="name" value="{{name}}">
</td>
<td>{{amount}}
<input type="hidden" name="amount" value={{amount}}>
</td>
<td>{{price}}
<input type="hidden" name="price" value={{price}}>
</td>
<td>{{sumprice}}
<input type="hidden" name="sumprice" value={{sumprice}}>
<input type="hidden" name="no_note" value={{no_nota}}>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<input type="hidden" name="no_nota" value={{no_nota}}>
<input type="hidden" name="total_nota" value={{sumcart}}>
<input type="hidden" name="tanggal" value={{now}}>
<h3> Your cart total is {{sumcart}}</h3>
<hr/>
<button type="submit" class="btn-success">Confirm</button>
</form>
Views.py
def transactionadd(request):
form1 = TransForm(request.POST or None)
form2 = TransDetailForm(request.POST or None)
if form1.is_valid() and form2.is_valid():
form1.save()
form2.save()
messages.success(request,"Transaction recorded")
Cart.objects.all().delete()
return redirect('index')
context={
'form1':form1,
'form2':form2
}
return render(request, 'cart.html', context)

问题是每次我确认事务时,只有一个条目行(最新对象(被输入到数据库中。假设我把一个汉堡包和一个热狗放进购物车并创建一个交易。在交易明细数据库中,我只会得到热狗,而不是汉堡包。我该如何解决这个问题?

似乎您的表单没有前缀,这就是为什么只使用最后一个。

如果要使用表单添加多个相同类型的对象,则应使用表单集:https://docs.djangoproject.com/en/3.0/topics/forms/formsets/

下面解释了如何使用javascript轻松添加新条目: https://simpleit.rocks/python/django/dynamic-add-form-with-add-button-in-django-modelformset-template/

最新更新