难以将文件上传到 FileField,表单无效

Difficulty uploading a file to a FileField, form isn't valid

晕,我正在尝试使用文件字段上传文件。但我总是失败。当语句 form.errors.as_data() 执行时,浏览器 return 'tempfile'。我已经尝试从 Django 文档和一些 Django 参考资料中找到解决方案。但是,还是修不了。 ;(

这是我的 view.py

def dataprocessing(request):
if request.method == 'POST':
    form = DocumentForm(request.POST, request.FILES)

    if form.is_valid():
       import pdb; pdb.set_trace()
       newdoc = Document(docfile=request.FILES['myfile'])
       newdoc.save()

       #Redirect to the dataprocessing after POST
       #return render(request, 'dataprocessing.html')
       return HttpResponse("success")
    else:
       return HttpResponse(form.errors.as_data())

else:
     import pdb; pdb.set_trace()
     form = DocumentForm() #A empty, unbound form

return render(request, 'dataprocessing.html', {'form': form})

models.py

class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')

forms.py

class DocumentForm(forms.Form):
tempfile = forms.FileField()

和dataprocessing.html

<form method="post" enctype="multipart/form-data" action="{% url "dataprocessing" %}">

                    <div class="form-group">
                        <label for="up">Input Data</label> {% csrf_token %}
                        <input type="file" name=myfile class="filestyle" data-buttonName="btn-primary" data-buttonBefore="true" data-size="sm" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                            id="up">
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary btn-block">Upload Data</button>
                        <button type="button" class="btn btn-primary btn-block">Download Template</button>
                    </div>
                </form>

像这样使用 forms.ModelForm instaed forms.Form 怎么样?

# forms.py
class DocumentForm(forms.Model):
    class Meta:
        model = Document
        fields = ['tempfile']

并让你的 views.py 像这样:

# views.py
def dataprocessing(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponse("success")
        else:
            return HttpResponse(form.errors.as_data())
    else:
        form = DocumentForm() #A empty, unbound form
    return render(request, 'dataprocessing.html', {'form': form})

这使得 form 对象可以直接保存到您的模型中。