使用Django进行文件上传:表单无效 [英] File upload with Django: Invalid form

查看:114
本文介绍了使用Django进行文件上传:表单无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首次发布问题。我基本上复制了我在这里和django文档网站上发现的所有内容,我无法弄清楚我在做什么不正确。

First time posting a question. I've basically copied everything I've found on here and on the django documentation site and I can't figure out what I'm doing incorrectly

这是代码从我的views.py文件

Here is the code from my views.py file

from django import forms

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file  = forms.FileField()

def upload_file(request):   
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        response = "Form is valid."              
    else:
        response = "Failed to upload attachment."
    return HttpResponse(response)

我的html文件:

 <form name="attachmentForm" action="http://mysite.com/uploadattachments" enctype="multipart/form-data" method="post">
      <p>
    Please specify a file, or a set of files:<br/>
    <input id="attachment" type="file" name="datafile" size="40"/>
      </p>
      <input type="submit" value="Send"/>
    </form>

当我测试它,我得到无法上传附件。有没有什么明显的,我在这里失踪?我有点新的django,所以我道歉,如果这只是一个愚蠢的错误。
提前感谢!

When I test it out I get "Failed to upload attachment". Is there anything obvious that I'm missing here? I'm a bit new to django as well so I apologize if it's just a dumb error. Thanks in advance!

推荐答案

不完全确定,但我猜想,因为你命名了在UploadFileForm类的定义中,文件标题中的名称属性必须匹配,即文件上传字段必须命名为文件,还必须有一个标题字段。

Not entirely sure on this, but I would guess that since you've named your form fields file and title in the definition of the UploadFileForm class, the name attribute of your form fields in the html has to match that, i.e. the file upload field has to be named "file", and there also has to be a "title" field.

我建议您查看 https://docs.djangoproject .com / en / dev / topics / forms / ,其中有如何自动或半自动呈现表单的示例。一旦您使用自动呈现的表单,您可以根据自己的需要进行自定义。

I'd recommend checking out https://docs.djangoproject.com/en/dev/topics/forms/ where there are examples on how to render the form automatically, or semi-automatically. Once you have it working with the automatically rendered form, you can customize it to your needs.

这篇关于使用Django进行文件上传:表单无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆