Reputation: 323
I am developing an application with django for uploading a file on the server. I have defined a form and a model in forms.py and models.py files separately as below(respectively):
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label=''
)
and in 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:
<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:
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!
Upvotes: 0
Views: 104
Reputation: 27513
in your view function
def pythonhandler(request):
data = DocumentForm(request.POST, request.FILES)
and in your html file
<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()" />
Upvotes: 1
Reputation: 323
I have missed enctype="multipart/form-data" command in my form tag in my HTML file. So, my form in the HTML file must be such as bellow:
<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()" />
Upvotes: 0