使用 Django 上传文件:表单无效
第一次发帖提问。我基本上复制了在这里和 django 文档网站上找到的所有内容,但我无法弄清楚我做错了什么
中的代码
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)
这是我的views.py文件和我的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 也有点陌生,所以如果这只是一个愚蠢的错误,我深表歉意。 提前致谢!
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
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)
And my html file:
<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>
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对此并不完全确定,但我猜测,由于您在 UploadFileForm 类的定义中命名了表单字段
file
和title
,因此name< html 中表单字段的 /code> 属性必须与之匹配,即文件上传字段必须命名为“file”,并且还必须有一个“title”字段。
我建议查看 https://docs.djangoproject.com/en/dev/ topic/forms/ 其中有有关如何自动或半自动呈现表单的示例。一旦您使用自动呈现的表单,您就可以根据您的需要对其进行自定义。
Not entirely sure on this, but I would guess that since you've named your form fields
file
andtitle
in the definition of the UploadFileForm class, thename
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.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.