Django won't upload and save document

Viewed 49

Can you see is there any problem? I don't have any errors, everything is showing but when I upload document, nothing happens, document is not uploaded. Everything seems as it should be, but something I missed, why won't upload document?

my_app/forms.py

class UploadFileForm(forms.Form):
    file = forms.FileField()

my_app/hendle_file.py

def handle_uploaded_file(f):  
    with open('my_app/static/upload/'+f.name, 'wb+') as destination:  
        for chunk in f.chunks():  
            destination.write(chunk)  

my_app/views.py

from .forms import UploadFileForm
from .handle_file import handle_uploaded_file
def upload_file(request):
    form = UploadFileForm()
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            print(form.cleaned_data)
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('file uploaded')
    else:
        form = UploadFileForm()
    return render(request, 'my_app/uploadfile.html', {'form': form})

my_app/template/my_app/uploadfile.html

{% extends "my_app/base.html" %}
{% block content %}

      <form method="post" enctype="multipart/form-data">
         {% csrf_token %}
         <h1>Upload your document!</h1>
         {{ form.as_p }}
         <input type="submit" type="button" value="Upload"
      </form>
{% endblock content %}
1 Answers

To upload a file within a form the enctype attribute has to be set to multipart/form-data

  <form method="post" enctype="multipart/form-data">
     {% csrf_token %}
     <h1>Upload your document!</h1>
     {{ form.as_p }}
     <input type="submit" type="button" value="Upload"
  </form>
Related