0
我想添加一個inlineformset到我的CreateView,因此用戶可以在父窗體中添加多個子項。表單生成正確,但是當我點擊提交按鈕時,什麼也沒有發生。Django的:Formset提交按鈕不工作
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>
你可以顯示你的模板? –
意識到我錯過了。它已被添加 – user3972986
我們都有相同的錯誤。我的帖子是[提交按鈕formset不起作用](http://stackoverflow.com/questions/34693617/uploading-multiple-images-in-django-for-a-single-post%22Subimit%20button%20do%20not %20work%22) – Pau