简体   繁体   English

Django表单传回form.is_valid False

[英]Django form returns form.is_valid False

This must be kind of basic issue but I am very new in Djnago and trying to learn how the forms work. 这一定是一个基本问题,但是我在Djnago还是一个新手,正在尝试学习表单的工作方式。 I have looked in different sites and forums but I haven't managed to understand what I am doing wrong. 我曾在不同的站点和论坛中查看过,但我还没有了解我做错了什么。

This is my form: 这是我的表格:

class UploadCSVForm(forms.Form):
   csv_file = forms.FileField()

Its a very simple form used in order to upload a CSV file. 它是用于上传CSV文件的非常简单的形式。

This is what I have in my view: 这是我的看法:

def layer_create(request, template='layers/layer_create.html'):
  if request.method == 'POST':

    form = UploadCSVForm(request.POST, request.FILES)
    #print form.is_bound  # THIS PRINTS TRUE
    #print (request.FILES['csv']) # THIS PRINTS THE FILE IN THE MEMORY

    if form.is_valid():
        print ("valid")
    else:
        print ("not valid")
        out = {'success': False}

    return HttpResponse('test site')

And this is the form in my Template: 这是我的模板中的表格:

<form id="file-uploader" method="post" enctype="multipart/form-data" action="{% url "layer_create" %}">
      <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
      <input type="file" id="file-input" name="csv" />
      <button type="submit" id="upload-button" class="btn btn-danger">Upload</button>
</form>

Using the function is_bound I see that there are actual data bound on the form. 使用函数is_bound我看到表单上绑定了实际数据。 And when I print: request.FILES['csv'] I can see the name of the file uploaded in the Memory. 当我打印时: request.FILES['csv']我可以在内存中看到上传文件的名称。

But I still get form.is_valid = False without ant errors or warnings. 但是我仍然得到form.is_valid = False而没有蚂蚁错误或警告。

You've named the field in the template csv , but the form is expecting it to be called csv_file . 您已经在模板csv命名了该字段,但是表单希望它被称为csv_file

Generally you should let Django output the fields in the template, which will avoid issues like this. 通常,您应该让Django输出模板中的字段,这样可以避免出现此类问题。 (It will also normally prepopulate the fields when redisplaying them after errors, although this doesn't happen for file fields for browser security reasons.) (在错误发生后重新显示它们时,通常也会预先填充这些字段,尽管出于浏览器安全性原因,文件字段不会发生这种情况。)

{{ form.csv_file }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM