在查看了一些预制的 CBV 后,我刚刚添加了自己的版本。multiple formsets -> one parent
我特别需要在单个视图中进行控制,每个视图都具有单独的保存功能。
我基本上将 FormSet 数据绑定填充到一个由andget_named_formsets
调用的函数中。get_context_data
form_valid
在那里,我检查所有表单集是否有效,并寻找一种方法,该方法可以formset.save()
在每个表单集的基础上覆盖普通旧表单以进行自定义保存。
模板通过以下方式呈现表单集
{% with named_formsets.my_specific_formset as formset %}
{{ formset }}
{{ formset.management_form }}
{% endwith %}
我想我会经常使用这个系统。
class MyView(UpdateView): # FormView, CreateView, etc
def get_context_data(self, **kwargs):
ctx = super(MyView, self).get_context_data(**kwargs)
ctx['named_formsets'] = self.get_named_formsets()
return ctx
def get_named_formsets(self):
return {
'followup': FollowUpFormSet(self.request.POST or None, prefix='followup'),
'action': ActionFormSet(self.request.POST or None, prefix='action'),
}
def form_valid(self, form):
named_formsets = self.get_named_formsets()
if not all((x.is_valid() for x in named_formsets.values())):
return self.render_to_response(self.get_context_data(form=form))
self.object = form.save()
# for every formset, attempt to find a specific formset save function
# otherwise, just save.
for name, formset in named_formsets.items():
formset_save_func = getattr(self, 'formset_{0}_valid'.format(name), None)
if formset_save_func is not None:
formset_save_func(formset)
else:
formset.save()
return http.HttpResponseRedirect('')
def formset_followup_valid(self, formset):
"""
Hook for custom formset saving.. useful if you have multiple formsets
"""
followups = formset.save(commit=False) # self.save_formset(formset, contact)
for followup in followups:
followup.who = self.request.user
followup.contact = self.object
followup.save()