我想创建一个表格供用户填写。
该表单由一个公司模型和一个员工模型组成。
我希望用户以一种形式添加一家公司和他们想要的尽可能多的员工。
在 django admin 中,使用 StackedInline 很容易实现此功能,但我需要做什么才能在我的公共表单中拥有相同的功能?
#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,
})