Django formset无效 - 为什么不呢?

时间:2017-01-24 14:56:55

标签: django formset

我正在尝试使用表单允许用户将图像上传到我的Django项目中存储在数据库中的项目,但是,我正在获得控制台输出,告诉我formset我正在使用无效......

我尝试用来将图像上传到项目的视图已定义为:

def upload_budget_pdfs(request, project_id):
    project = Project.objects.get(id=project_id)
    print("Value of project in 'upload_budget_pdfs()': ", project)

    presentations = project.budget_versions.select_related('meeting').prefetch_related('budget_items', 'cci_items', 'presenters').filter(version_number__isnull=False).annotate(vn=F('version_number') * -1).order_by('presentation_date', 'created', '-vn')
    print("Value of presentations in 'upload_budget_pdfs()': ", presentations)
    drawing_formset = DrawingUploadFormset(prefix="drawings", queryset=Drawing.objects.filter(budget__in=presentations).order_by('budget__presentation_date', 'budget__created'))
    print("Value of drawing_formset in 'upload_budget_pdfs()': ", drawing_formset)

    if drawing_formset.is_valid():
        print 'Saving drawing_formset'
        print "Before", [b.id for b in project.budget_versions.all()]
        for drawing_form in drawing_formset:
            if drawing_form.instance.budget:
                print 'Instance', drawing_form.instance.budget
                drawing = drawing_form.save(commit=False)
                drawing.budget = drawing_form.instance.budget
                drawing.save()
            print drawing, [b.id for b in project.budget_versions.all()]
    else: print 'Drawing formset not valid.',drawing_formset.errors

    budget_formset = BudgetPresentationFormset(request.POST, request.FILES, instance=project, prefix="presentations")

    if budget_formset.is_valid() and budget_formset.has_changed():
        updated_budget_presentations = budget_formset.save()
    elif budget_formset.has_changed(): print 'Budget formset not valid.',budget_formset.errors



    return HttpResponseRedirect(reverse('projects:concept', args=[project_id]))

和调用此视图时我得到的控制台输出是:

  

(“'upload_budget_pdfs()':”项目的价值,<项目:测试1>)

     

(“'upload_budget_pdfs()'中的演示文稿的价值:”,[&lt;预算:测试1:版本-1&gt;,&lt;预算:测试1:版本-1&gt;,&lt;预算:测试1 :版本0&gt;,&lt;预算:测试1:版本0&gt;,,,,,,,,,,,,,,,,'...(其余元素被截断)...'])< / p>      

(“upload_budget_pdfs()'中的drawing_formset的值:”,&lt; django.forms.formsets.DrawingFormFormSet对象位于0x10cee3790&gt;)

     

绘图formset无效。 []

所以很清楚,我视图中的else语句是在这里运行的,但我不确定为什么,因为控制台清楚地表明变量都保存了正确的数据... < / p>

我在这里初始化drawing_formset变量的方式有什么问题? queryset我传入DrawingUploadFormset(...)是否正确? is_valid()实际检查了什么?

修改

我在接受的答案中做了更改,以便我现在宣布drawing_formset

        drawing_formset = DrawingUploadFormset(request.POST, request.FILES, prefix="drawings", queryset=Drawing.objects.filter(budget__in=presentations).order_by('budget__presentation_date', 'budget__created'))

但似乎我现在收到了“内部服务器错误”并且MultiValueDictKeyError就行了:

for drawing_form in drawing_formset: #This line is what's causing the MultiValueDictKeyError

我不明白为什么会这样?有什么建议吗?

1 个答案:

答案 0 :(得分:3)

您的formset不包含任何数据。您需要将request.POSTrequest.FILES作为第一个和第二个参数(或datafiles关键字参数),但前提是它是实际的表单提交。

如果没有数据传递到表单或表单集,则会将其视为未绑定,并且将在不检查错误的情况下返回False

通常的模式是在request.method == 'POST'时传递它们,然后验证formset:

def upload_budget_pdfs(request, project_id):
    ...
    if request.method == 'POST':
        drawing_formset = DrawingUploadFormset(request.POST, request.FILES, prefix='drawings', queryset=...)
        if drawing_formset.is_valid():
            # save formset
            return HttpResponseRedirect(...)
    else:
        drawing_formset = DrawingUploadFormset(prefix='drawings', queryset=...)
    return render(...)  # Render formset

这将在GET上显示一个空白表单,这是一个填写表单,在提交失败时会显示错误消息,它将保存表单集并重定向成功提交。