我正在尝试向我的CreateView添加一个inlineformset,以便用户可以在Parent窗体中添加多个Children。表单生成正确但当我单击提交按钮时没有任何反应。
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>
答案 0 :(得分:0)
当我将主要表单正文放在<table> ... </table>
<form id="CreateExamForm" method="POST" enctypr="multipart/form-data">
{% csrf_token %}
<table>
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Classe - Matière - Date</h3>
<span class="pull-right"><i class="glyphicon glyphicon-chevron-up"></i></span>
</div>
<div class="panel-body">
{% crispy doc_form %}
{{ file_form_set.management_form }}
{% for f_form in file_form_set %}
<div class="form-inline">
{% crispy f_form %}
</div>
{% endfor %}
</div>
</div>
</table>
<input type="submit" value="Add recipe" class="submit" />
</form>