在ModelForm中内联

Tom*_*sen 15 django django-forms

我想创建一个表单供用户填写.

表单由公司模型和员工模型组成.

我希望用户以一种形式添加一个公司和他们想要的员工数量.

在Django管理,这个功能很容易与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        
Run Code Online (Sandbox Code Playgroud)
#admin.py
class EmployeeInline(admin.StackedInline):
    model = Employee


class CompanyAdmin(admin.ModelAdmin):

    inlines = [
        EmployeeInline,
    ]

    model = Company

admin.site.register(Company, CompanyAdmin)
Run Code Online (Sandbox Code Playgroud)
#forms.py

class CompanyForm(ModelForm):
    class Meta:
        model = Company

class EmployeeForm(ModelForm):
    class Meta:
        model = Employee
Run Code Online (Sandbox Code Playgroud)
#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,
    })            
Run Code Online (Sandbox Code Playgroud)

ale*_*cxe 12

内联表单集是您所需要的:

内联表单集是模型表单集之上的一个小抽象层.这些简化了通过外键处理相关对象的情况.

看这里的例子:

希望有所帮助.