[Answer]-Django form, handle multiple entities creation

1👍

Inline model formsets are what you want.

0👍

Consider this as your models.py

class Project(models.Model):
    project = models.Charfield(max_length=100)

class Feature(models.Model):
    name = models.Charfield(max_length=100)
    project = models.ManyToManyField(Project, blank = True)

forms.py:

class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project

Rough code snippets for views.py:

def project(request):
    ModelForm = inlineformset_factory(Project, Feature)
    if request.method == 'POST':
        form = ProjectForm(request.POST)
        project = Project.objects.get(pk=request.pk)
        formset = ModelForm(instance=project)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('')
    else:
        form = ProjectForm()
        formset = ModelForm()    
        return render_to_response('project.html', {'form':
form, 'formset': formset})

Leave a comment