gpt4 book ai didi

带有formset的django保存模型

转载 作者:行者123 更新时间:2023-12-04 23:48:29 24 4
gpt4 key购买 nike

我有以下 View 代码

account = PatientAccount.objects.get(pk=account_id)
payments = Payments.objects.filter(account=account)
total_cost = 0
for hasjob in account.hasjobs.all().select_related('job'):
total_cost += hasjob.quantity * hasjob.job.cost*(1.0 - hasjob.discount / 100.0)

PaymentFormset = modelformset_factory(Payments, form=PaymentModelForm, can_delete=False)
formset = PaymentFormset(request.POST or None, queryset=payments)

if request.method == 'POST':
print formset.is_valid()
if formset.is_valid():
for form in formset:
if form.is_valid():
try:
if form.cleaned_data.get('DELETE') and form.instance.pk:
form.instance.delete()
else:
instance = form.save(commit=False)
print instance.pk
instance.account = account
print instance.account
instance.save()
messages.success(request, "Payments saved successfully")
except DatabaseError:
messages.error(request, "Database error. Please try again")

return redirect('job_management-edit', account_id=account.pk)

但它不会保存模型。一切正常,因为它应该 formset is valid form is valid。

最佳答案

问题似乎是您从 内部返回响应。 for 循环 .

试试这个:

account = PatientAccount.objects.get(pk=account_id)
payments = Payments.objects.filter(account=account)
total_cost = 0
for hasjob in account.hasjobs.all().select_related('job'):
total_cost += hasjob.quantity * hasjob.job.cost*(1.0 - hasjob.discount / 100.0)

PaymentFormset = modelformset_factory(Payments, form=PaymentModelForm, can_delete=False)
formset = PaymentFormset(request.POST or None, queryset=payments)

if request.method == 'POST':
print formset.is_valid()
if formset.is_valid():
for form in formset:
if form.is_valid():
try:
if form.cleaned_data.get('DELETE') and form.instance.pk:
form.instance.delete()
else:
instance = form.save(commit=False)
print instance.pk
instance.account = account
print instance.account
instance.save()
messages.success(request, "Payments saved successfully")
except DatabaseError:
messages.error(request, "Database error. Please try again")

return redirect('job_management-edit', account_id=account.pk)

关于带有formset的django保存模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28543735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com