[Django]-How to save Django ModelFormSet?

1👍

As I said in the comment, it doesn’t make sense to pass a queryset of Employees to the instantiation of the Salary formset. I think given you’re trying to keep these two models completely separate for whatever reason, and you want to create new Salary instances each time, you would be better off just passing a set of initial data.

This is slightly tricky, because initial only applies to extra forms, and extra is set by the formset factory, so you need to do it in the view. Something like this:

employees = Employee.objects.values('name', 'surname')
SalaryFormSet = modelformset_factory(Salary, extra=len(employees))
formset = SalaryFormSet(initial=employees, queryset=Salary.objects.none())

1👍

This is just to summarize the answer, based on Daniel Roseman’s solution.

In models.py:

class Employee(models.Model):
    surname = models.CharField(max_length=100)
    name = models.CharField(max_length=100)


class Salary(models.Model):
    date = models.DateField(auto_now_add=True)
    surname = models.CharField(max_length=100)
    name = models.CharField(max_length=100)
    salary = models.DecimalField(max_digits=20, decimal_places=2)

In forms.py:

employees = Employee.objects.values('surname', 'name')
SalaryFormSet = modelformset_factory(Salary, extra=len(employees)

In views.py:

def createForm(request):
    formset = SalaryFormSet(initial=employees, queryset=Salary.objects.none())
    return render(request, 'formfile.html', {'formset': formset})

def submitForm(request)
    f = ModelBFormSet(request.POST)
    if f.is_valid():
        f.save()
        return HttpResponse('Submitted successfully')
    else:
        return HttpResponse(f.errors, request.POST)

Leave a comment