(我在django很新,我用Google搜索了很多,但找不到答案,所以我希望你不介意低级问题) 有这些类:
class Cl(models.Model):
user = models.ForeignKey(User,editable=False)
title = models.CharField(max_length=100)
class Member(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
cl = models.ForeignKey(Cl)
class ClForm(ModelForm):
class Meta:
model = Cl
我想创建一个页面,我可以创建一个Cl的对象和一些相关的成员对象(我打算使用django-dynamic-formset,但这不是重点)。我的观点如下:
class NewView(TemplateView):
def get(self, request):
cform = ClForm(prefix="cl", instance=Cl(user=request.user))
MemberFormSet = modelformset_factory(Member)
memberfs = MemberFormSet(queryset=Member.objects.none())
return render_to_response(self.template_name, {'cl_form': cform, 'memberformset': memberfs}, context_instance=RequestContext(request))
def post(self,request):
cform = ClForm(request.POST, prefix="cl", instance=Cl(user=request.user))
MemberFormSet = modelformset_factory(Member)
memberfs = MemberFormSet(request.POST)
if cform.is_valid() and memberfs.is_valid():
new_cl = cform.save()
new_members = memberfs.save(commit=False)
for mf in new_members:
mf.cl = new_cl
mf.save()
return HttpResponseRedirect("unimportant")
return render_to_response(self.template_name, {'cl_form': cform, 'memberformset': memberfs}, context_instance=RequestContext(request))
我的模板如下所示:
<form id="myForm" method="post" action="">
{% csrf_token %}
{{ memberformset.management_form }}
<table>
{{ cl_form }}
<tr><th colspan="2">Members</th></tr>
{% with memberformset.empty_form as form %}
<div id="id_empty_form" style="display:none;">
{{ form }}
</div>
{% endwith %}
</table>
<input type="submit" value="Save" />
</form>
我现在的问题是,该成员未被存储。此外,memberfs.is_valid()也不会抱怨,例如电子邮件字段未正确填写。 我也尝试了inlineformset_factory,但这也没有用。
答案 0 :(得分:0)
我认为问题在于您在该模板中使用“empty_form”。 here描述了使用formset的正确方法。在您的示例中,您应该写:
<form id="myForm" method="post" action="">
{% csrf_token %}
{{ memberformset.management_form }}
<table>
{{ cl_form }}
<tr><th colspan="2">Members</th></tr>
<!-- THIS IS NOT NECESSARY UNLESS YOU WANT TO ADD FORMS WITH JAVASCRIPT-->
<div id="id_empty_form" style="display:none;">
{{ memberformset.empty_form }}
</div>
<!-- END NOT NECESSARY-->
{% for form in memberformset.forms %}
{{ form }}
{% endfor %}
{% endwith %}
</tbody>
</table>
<input type="submit" value="Save" />
</form>