I want to create a form for users to fill out.
The form consist of a Company model, and a Employee model.
I want users to add one company and as many Employee they want, in one form.
In django admin, this functionality is easy to accomplish with StackedInline, but what do I need to do, to have the same functionality in my public form?
#models.py
class Company(models.Model):
name = models.CharField()
def __unicode__(self):
return self.name
class Employee(models.Model):
company = models.ForeignKey(Company)
first_name = models.CharField()
last_name = models.CharField()
def __unicode__(self):
return self.first_name
#admin.py
class EmployeeInline(admin.StackedInline):
model = Employee
class CompanyAdmin(admin.ModelAdmin):
inlines = [
EmployeeInline,
]
model = Company
admin.site.register(Company, CompanyAdmin)
#forms.py
class CompanyForm(ModelForm):
class Meta:
model = Company
class EmployeeForm(ModelForm):
class Meta:
model = Employee
#views.py
def companyform_view(request):
if request.method == 'POST':
form = CompanyForm(request.POST)
if form.is_valid():
f = CompanyForm(request.POST)
f.save()
return HttpResponseRedirect('/company/added/')
else:
form = CompanyForm()
return render(request, 'form/formtemplate.html', {
'form': form,
})
Inline formsets is what you need:
Inline formsets is a small abstraction layer on top of model formsets. These simplify the case of working with related objects via a foreign key.
See examples here:
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With