我想创建一个表单供用户填写。
表单由公司模型和员工模型组成。
我希望用户以一种形式添加一个公司和他们想要的员工。
在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,
})
答案 0 :(得分:9)