[英]uploading a file using django
I am developing an application with django for uploading a file on the server. 我正在使用django开发用于在服务器上上传文件的应用程序。 I have defined a form and a model in forms.py and models.py files separately as below(respectively):
我分别在forms.py和models.py文件中定义了一个表单和一个模型,如下所示(分别):
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label=''
)
and in models.py: 并在models.py中:
from django.db import models
# Create your models here.
class Document(models.Model):
docfile = models.FileField(upload_to='targetdir')
in my HTML file and my form is: 在我的HTML文件中,我的表单是:
<form class="myclass" action="submit" method="post">
{% csrf_token %}
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<br />
<input font-size="50px" style="zoom:1.5" class="myclass" dir="rtl" type="submit" value="upload" id="button" class="top-menu" onclick="pythonhandler()" />
now, whenever I submit my form and I wanna to receive my uploaded file on the server via below codes, I got " 现在,每当我提交表单并想要通过以下代码在服务器上接收上传的文件时,我都会得到“
raise MultiValueDictKeyError(repr(key))
MultiValueDictKeyError: "'docfile'""
error. 错误。 my views.py file:
我的views.py文件:
def pythonhandler(request):
if request.method == 'POST':
try:
data = request.FILES.get('docfile')
with open(os.getcwd()+'/mydirectory/'+request.FILES['docfile'].name, 'wb+') as destination:
for chunk in request.FILES['docfile'].chunks():
destination.write(chunk)
I did the mentioned steps in this , this and this question, but I receive this error again! 我在this , this和this问题中执行了上述步骤,但是我再次收到此错误!
in your view function 在您的视图功能中
def pythonhandler(request):
data = DocumentForm(request.POST, request.FILES)
and in your html file 并在您的html文件中
<form class="myclass" action="submit" enctype="multipart/form-data" method="post">
{% csrf_token %}
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<input type="submit" value="upload" id="button" class="top-menu" onclick="pythonhandler()" />
I have missed enctype="multipart/form-data" command in my form tag in my HTML file. 我在HTML文件的表单标记中错过了enctype =“ multipart / form-data”命令。 So, my form in the HTML file must be such as bellow:
因此,HTML文件中的表单必须如下所示:
<form class="myclass" action="submit" enctype="multipart/form-data" method="post">
{% csrf_token %}
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<input type="submit" value="upload" id="button" class="top-menu" onclick="pythonhandler()" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.