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

loading...


0

按照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为空,我不能这样做 .

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

loading...

1回答

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

    将你的形式改为上层

评论

暂时没有评论!