gpt4 book ai didi

django - 在 ModelForm 中内联

转载 作者:行者123 更新时间:2023-12-03 20:49:00 26 4
gpt4 key购买 nike

我想创建一个表格供用户填写。

该表单由一个公司模型和一个员工模型组成。

我希望用户以一种形式添加一家公司和他们想要的尽可能多的员工。

在 django admin 中,使用 StackedInline 很容易实现此功能,但我需要做什么才能在我的公共(public)表单中拥有相同的功能?

#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是你需要的:

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.



请参阅此处的示例:
  • Creating a model and related models with Inline formsets

  • 希望有帮助。

    关于django - 在 ModelForm 中内联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18764880/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com