0

(我是 django 的新手,我用谷歌搜索了很多但找不到答案,所以我希望你不介意这个低级问题)有这些类:

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,但这也没有用。

4

1 回答 1

0

我认为问题在于您在该模板中使用了“ empty_form ”。此处描述了使用表单集的正确方法。在您的示例中,您应该编写:

<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>
于 2013-03-13T03:33:38.003 回答