inlineformset_factory 只为嵌套元素提供多个表单,如果您想要主模型的表单,则需要在顶部提供一个单独的表单。
这是一个工作 inlineformset_factory 的示例,主窗体嵌入在顶部:
视图.py
from django.shortcuts import get_object_or_404, render_to_response
from django.forms.models import inlineformset_factory
from django.http import HttpResponseRedirect
from django.template import RequestContext
from App_name.models import * #E.g. Main, Nested, MainForm, etc.
. . .
@login_required
def Some_view(request, main_id=None, redirect_notice=None):
#login stuff . . .
c = {}
c.update(csrf(request))
c.update({'redirect_notice':redirect_notice})#Redirect notice is an optional argument I use to send user certain notifications, unrelated to this inlineformset_factory example, but useful.
#Intialization --- The start of the view specific functions
NestedFormset = inlineformset_factory(Main, Nested, can_delete=False, )
main = None
if main_id :
main = Main.objects.get(id=main_id)#get_object_or_404 is also an option
# Save new/edited Forms
if request.method == 'POST':
main_form = MainForm(request.POST, instance=main, prefix='mains')
formset = NestedFormset(request.POST, request.FILES, instance=main, prefix='nesteds')
if main_form.is_valid() and formset.is_valid():
r = main_form.save(commit=False)
#do stuff, e.g. setting any values excluded in the MainForm
formset.save()
r.save()
return HttpResponseRedirect('/Home_url/')
else:
main_form = MainForm(instance=main, prefix='mains') #initial can be used in the MainForm here like normal.
formset = NestedFormset(instance=main, prefix='nesteds')
c.update({'main_form':main_form, 'formset':formset, 'realm':realm, 'main_id':main_id})
return render_to_response('App_name/Main_nesteds.html', c, context_instance=RequestContext(request))
模板.html
{% if main_form %}
<form action="." method="POST">{% csrf_token %}
{{ formset.management_form }}
<table>
{{main_form.as_table}}
{% for form in formset.forms %}
<table>{{ form }}</table>
{% endfor %}
</table>
<p><input type="submit" name="submit" value="Submit" class="button"></p>
</form>
{% endif %}