保存formset文件字段失败

时间:2014-04-29 08:47:45

标签: python django forms file-upload formset

尝试在formset中保存fileField,但调试返回UploadPdfFormSet'对象没有属性' save'。感觉像缺少处理文件集中文件的文档。你们有什么可以帮助我的吗?

forms.py

    from django import forms

class UploadPdf(forms.Form):
    docfiles = forms.FileField(label='Browse')

class UploadPdfUrl(forms.Form):
    docurl = forms.URLField(label='Address')

views.py

    def upload(request):    
        UploadPdfFormSet = formset_factory(UploadPdf)
        if request.method == 'POST':
            formsetFile = UploadPdfFormSet(request.POST, request.FILES)     
            if formsetFile.is_valid():
                instances = formsetFile.save
                for form in instances:
                    form.save()

                return HttpResponse('yey')
        else:
            formsetFile = UploadPdfFormSet()
            formURL = UploadPdfUrl

        return render(request, 'pdfchecker/index.html', {
            'formsetFile': formsetFile, 'formURL': formURL,
            })



UPDATE: New view.py file which successfully saves file:

def upload(request):

    UploadPdfFormSet = formset_factory(UploadPdf)
    handleUploadPdfFormSet = modelformset_factory(handle_UploadPdf)
    if request.method == 'POST':
        formsetFile = UploadPdfFormSet(request.POST, request.FILES)
        formsetHandle = handleUploadPdfFormSet(request.POST, request.FILES)
        if formsetFile.is_valid():
            formsetHandle.save()

            return HttpResponse('yey')
    else:
        formsetFile = UploadPdfFormSet()
        formURL = UploadPdfUrl

    return render(request, 'pdfchecker/index.html', {
        'formsetFile': formsetFile, 'formURL': formURL,
        })

1 个答案:

答案 0 :(得分:0)

看起来您指的是this文档示例。但是这个例子都是关于ModelFormsets的,而不是你正在使用的常规formset。 save方法在这里没有意义。所以你有两个选择:

  • 使用ModelFormsets(当然,如果您的应用中有与UploadPdf表单相对应的模型)
  • (更有可能)手动使用formset cleaning_data执行这些操作。就像在this示例中一样。