I'm quite desperate now and I cannot figure this out. To me it should be easy to do, but I have not come across any answers that explains this.
Two models with no foreign keys between them:
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)
One modelformset to save to ModelB.
SalaryFormSet = modelformset_factory(Salary, extra=0)
Then in views.py:
def createForm(request):
formset = SalaryFormSet(queryset=Employee.objects.all())
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)
In formfile.html:
<form action="submitForm/" method="post">
{{ formset.management_form }}
<table>
{{ formset }}
</table>
{% csrf_token %}
<input type="submit" value="Submit">
</form>
As soon as I hit Submit, the formset is parsed as invalid and f.errors states (for each row in Employee):
<ul class="errorlist"><li>id<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>
I just want to have surname and name from all rows in Employee preloaded into SalaryFormSet, and I should enter salary for each row and save them to Salary. The records in Salary should not be updated, but a new entry should be created.
The Employee model already has records created from the admin site. As employees' salaries increase, I will generate payslips from Salary model and capture the relevent salary from the latest date.
If I change the queryset to queryset=Salary.objects.none() and change SalaryFormSet to extra=2, the template is rendered empty. If I insert surnames, names and salary manually, the formset saves correctly. Two new entries in Salary. Why can't I just have the name preloaded (should I load them as str()?) and manually add the salary?