简体   繁体   中英

uploading a file using django

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!

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()" />

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()" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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