【发布时间】:2021-08-28 06:18:36
【问题描述】:
模型.py
class Record(models.Model):
items = models.ManyToManyField(Item, blank=True)
...
class Item(models.Model):
PAYMENT_CLASSIFICATION = (
('earning','Earning'),
('deduction','Deduction'),
('reimbursement','Reimbursement')
)
payment_classification = models.CharField(max_length=20, null=True,
choices=PAYMENT_CLASSIFICATION)
user_to_input = models.CharField(max_length=20, null=True)
...
class EachRowItem(models.Model):
item = models.ForeignKey(Item,on_delete=models.SET_NULL, null=True)
record = models.ForeignKey(Record,on_delete=models.SET_NULL, null=True)
paid_amount = models.DecimalField(max_digits=10, decimal_places =2, null=True, blank=True )
unit = models.DecimalField(max_digits=10, decimal_places =2, null=True, blank=True )
form.py
class EachRowItemForm(forms.ModelForm):
class Meta:
model = EachRowItem
exclude = ['record']
view.py
def PayRecordUpdate(request, pk):
form = EachItemForm(request.POST or None)
record = Record.objects.get(pk=pk)
if request.is_ajax():
item = request.POST.get('item')
paid_amount = request.POST.get('paid_amount')
unit = request.POST.get('unit')
if form.is_valid():
record = Record.objects.get(pk=pk)
instance = form.save(commit=False)
instance.record = record
record.items.add(item)
record.save()
instance.save()
return JsonResponse({
'item': instance.item,
'paid_amount': instance.paid_amount,
'unit': instance.unit,
})
context ={
'record': record,
'form':form,
}
return render(request, '/update_record.html', context)
在模板中,我有一个弹出模式来填写 EachItemForm 表单。因此有 is_ajax()。我可以得到有效的表格。
| Item | paid amount | unit |
|---|---|---|
| Earning | ||
| Item A1 | 2.00 | 2 |
| Item A2 | 1.00 | 2 |
| ----- | ----------- | ---- |
| Deduction | ||
| Item B1 | -2.00 | 1 |
| Item B2 | -1.00 | 1 |
| ----- | ----------- | ---- |
| Reimbursement | ||
| Item C1 | 2.00 | 1 |
| Item C2 | 1.00 | 1 |
但是,我在 update_record.html 中呈现问题,其中项目被相应地排列为分类。该功能必须以在不同页面中设置项目的方式进行。例如,ItemB1 是设置扣除。记录可以在 update_record.html 模板中添加任何项目。商品可以有不同的数量和单位,需要在 EachItemForm 表单中键入记录。
我在下面尝试过,但结果不是我需要的。我不太确定模型外键或模型设置是否可以以更简单的方式完成,或者是否需要将过滤后的查询呈现到模板中。请帮忙。
{% if record.items.all %}
{% for item in record.items.all %} # In the Record__Item now then how to access Item__EachRowItem from here?
{% if item.payment_classification == "earning" %}
{{ item }}
{{ item.paid_amount }}
{{ item.unit }}
{% endif %}
{% endfor %}
{% endif %}
【问题讨论】:
-
你好@bewbie 我的回答解决了你的问题吗?
标签: python html django django-models django-templates