Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django saving model with formset

Tags:

django

formset

I have the following view code

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)

But It won't save the models. Everything works as it should formset is valid form is valid.

like image 494
Apostolos Avatar asked Feb 10 '23 21:02

Apostolos


1 Answers

The problem seems to be that you are returning the response from inside the for loop.

Try this instead:

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)
like image 56
Ankit Popli Avatar answered Feb 13 '23 21:02

Ankit Popli