request.FILES为空,尽管请求中存在文件

时间:2018-12-10 12:24:49

标签: django django-forms

按照django website上的示例,我正在尝试上传文件,对内容进行检查,然后反馈给用户并存储文件内容。

但是,request.FILES总是空的,我遇到了麻烦。我的代码如下(注意print语句后的输出):

**forms.py**
class UploadFileForm(forms.Form):
    data_import = forms.FileField()

    class Meta:
        model = Recipe
        fields = ('data_import',)


**view**
def recipes_list(request):
    template = 'recipes/recipes_list.html'

    if request.method == 'GET':
        user = request.user
        queryset = Recipe.objects.filter(user=user)
        form = UploadFileForm()
        return render(request, 'recipes/recipes_list.html', context={'recipes': queryset, 'form': form})

    elif request.method == 'POST':
        print(request.FILES) # <MultiValueDict: {}>
        print(request.POST) # <QueryDict: {'csrfmiddlewaretoken': ['...'], 'data_import': ['recette.json']}>
        form = UploadFileForm(request.POST, request.POST.data_import)

        if form.is_valid():
            return HttpResponseRedirect(template)
        else:
            print(form.errors)


**template**
<form method="post">
    {% csrf_token %}
    {{ form }}
    <button type="submit">submit</button>
</form>  

我得到的错误是:

<ul class="errorlist"><li>data_import<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

但是我可以看到该文件已上传,并且位于request.POST.get('data_import')中。

我想在表单上运行验证,但是如果request.FILES为空,我将无法执行此操作。

我显然做错了什么,有人可以指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

<form method="post" enctype= multipart/form-data>
    {% csrf_token %}
    {{ form }}
    <button type="submit">submit</button>
</form> 

将表格更改为上一页