【发布时间】:2020-01-26 04:43:13
【问题描述】:
我有一个 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)
问题是每次我确认交易时,只有一个输入行(最新的对象)被输入到数据库中。假设我将汉堡包和热狗放入购物车并创建交易。在交易明细数据库中,我只会得到热狗而不是汉堡包。我该如何解决这个问题?
【问题讨论】: