基于类的视图仍然是新的,因此我将其写出来。过程很简单:
首先,为您的对象创建表单。其中一种形式将重复。这里没有什么特别的。
class SonInline(ModelForm): model = Sonclass FatherForm(ModelForm): model = Father
然后,创建您的
formset:
FatherInlineFormSet = inlineformset_factory(Father, Son, form=SonInline, extra=1, can_delete=False, can_order=False)
现在,将其与您的集成
CreateView:
class CreateFatherView(CreateView): template_name = 'father_create.html' model = Father form_class = FatherForm # the parent object's form # On successful form submission def get_success_url(self): return reverse('father-created') # Validate forms def form_valid(self, form): ctx = self.get_context_data() inlines = ctx['inlines'] if inlines.is_valid() and form.is_valid(): self.object = form.save() # saves Father and Children return redirect(self.get_success_url()) else: return self.render_to_response(self.get_context_data(form=form)) def form_invalid(self, form): return self.render_to_response(self.get_context_data(form=form)) # We populate the context with the forms. Here I'm sending # the inline forms in `inlines` def get_context_data(self, **kwargs): ctx = super(CreateFatherView, self).get_context_data(**kwargs) if self.request.POST: ctx['form'] = FatherForm(self.request.POST) ctx['inlines'] = FatherInlineFormSet(self.request.POST) else: ctx['form'] = Father() ctx['inlines'] = FatherInlineFormSet() return ctx
最后,这是模板:
关键部分是jQuery django-dynamic-formset插件,该插件不断添加新的内联表单:
<form id="father-form" method="POST" enctype="multipart/form-data" action=".">{% csrf_token %}<div > {% for f in form %} <div >{{ f.label }}<br />{{ f }} {% if f.errors %} {% for v in f.errors %} <br /><span >{{ v }}</span> {% endfor %} {% endif %} </div> {% endfor %}</div><hr /><h2>Sons:</h2><table > <table> {% for f2 in inlines %} <tr id="{{ f2.prefix }}-row"> {% for i in f2 %} <td>{{ i }}{% if i.errors %}<span >{{ i.errors }}</span>{% endif %} </td> {% endfor %} </tr> {% endfor %}</table>{{ inlines.management_form }}<input type="submit" value="Go Go Gadget →"></form><script type="text/javascript"> $(function() { $('#father-form tr').formset({ prefix: '{{ inlines.prefix }}' }); })</script>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)