重复的模型在modelformset中没有验证 - django

时间:2013-01-08 20:05:18

标签: django modelform

我有一个ModelForm,用户可以提交该信息以将信息保存到数据库。我想用ModelFormset扩展它,以便用户可以同时查看和提交具有不同信息的多个相同模型表单。但是,我的POST数据没有绑定到ModelFormset,因此ModelFormset在is_valid()上失败为无效。我看到有与request.POST.copy()相关的数据,只是

views.py

def create(request):
    if request.method == 'POST':
        post_data = request.POST.copy()
        print "POST DATA"
        print post_data
        for i in post_data:
            print i
        formSet = WorkOrder_Form(post_data)
        print "FORMSET"
        print formSet
        if formSet.is_valid():
            formSet.save()
        else:
            print 'INVALID'
        return HttpResponseRedirect('/Shelling/') 
    else:
        formSet = formset_factory(WorkOrder_Form, extra=1)
        return render_to_response('create.html',{'WorkOrder_Form':formSet}, context_instance=RequestContext(request))

template:(create.html)

{% load url from future %}
<a href="{% url 'index' %}"> Return to Index </a></li>
<br>
<br>
<form action="{% url 'create' %}" method="post"> {% csrf_token %}


{% for WorkOrder in WorkOrder_Form %}
    {{ WorkOrder.as_ul }}
    <br>
{% endfor %}

1 个答案:

答案 0 :(得分:1)

您使用的是模型表单,因此您应该使用modelformset_factory而不是formset_factory。您可以在create视图之外创建formset类。然后,您需要在视图的GET POST分支中实例化formset。

把它放在一起,你有以下(未经测试,所以可能会有一些拼写错误!)

WorkOrderFormSet = formset_factory(WorkOrder_Form, extra=1)

def create(request):
    if request.method == 'POST':
        post_data = request.POST.copy()
        formset = WorkOrderFormSet(data=post_data, queryset=WorkOrder.objects.none())
        if formset.is_valid():
            formset.save()
        else:
            print 'INVALID'
        return HttpResponseRedirect('/Shelling/') 
    else:
        formset = WorkOrderFormSet(queryset=WorkOrder.objects.none())
        return render_to_response('create.html',{'formset':formset}, context_instance=RequestContext(request))

在模板中:

{% for form in formset %}
    {{ form.as_ul }}
{% endfor %}