I am trying to add an inlineformset to my CreateView so users can add multiple Children within the Parent form. The form generates properly but when I click the submit button nothing happens.
models.py
class Parent(models.Model):
...
class Child(models.Model):
parent = models.ForeignKey(Parent)
...
views.py
class ParentCreate(CreateView):
model = Parent
form_class = ParentForm
def get(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
Child_form = ChildFormSet()
return self.render_to_response(
self.get_context_data(form=form,
child_form=child_form,
formset=ChildFormSet))
def post(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
child_form = ChildFormSet(self.request.POST)
if form.is_valid() and child_form.is_valid():
return self.form_valid(form, child_form)
else:
return self.form_invalid(form, child_form)
def form_valid(self, form, child_form):
self.object = form.save()
child_form.instance = self.object
child_form.save()
return HttpResponseRedirect(self.get_success_url())
def form_invalid(self, form, child_form):
return self.render_to_response(
self.get_context_data(form=form,
child_form=child_form,
formset=ParentFormSet))
forms.py
class ParentForm(ModelForm):
class Meta:
model = Parent
exclude = ('creation', 'last_modified')
ChildFormSet = inlineformset_factory(Parent, Child, extra=10,
exclude=('creation', 'last_modified'), can_delete=False)
template.html
<form method="POST" action=".">{% csrf_token %}
{{ form|crispy }}
{% crispy formset %}
<input class="btn btn-primary" type="submit" value="Submit" />
</form>