Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline in ModelForm

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,
    })            

like image 280
Tomas Jacobsen Avatar asked Sep 12 '13 12:09

Tomas Jacobsen


1 Answers

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:

  • Creating a model and related models with Inline formsets

Hope that helps.

like image 119
alecxe Avatar answered Oct 04 '22 13:10

alecxe