Django file upload is not uploading the file?

I have created a file upload something like this:

DataUpload is the view that handles template rendering and handle_uploaded_file is the function that reads the file.

View.py

def DataUpload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
       
        if form.is_valid():
            print(request.FILES['file'])
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()
    return render(request, 'DataBase/upload.html', {'form': form})
  
def handle_uploaded_file(f):
    with open(os.getcwd()+f, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

url

url(r'DataUpload', views.DataUpload, name='DataUpload'),

forms.py

from django import forms


class Rand_Frag_From(forms.Form):

    Seq = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Tropomyosin beta chain '}),required=False)
    Acc = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'P02671 '}), required=True)

 

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

template

{% load static %}

<link rel="stylesheet" href="{% static 'css/table/custom.css' %}">

<div class="main">
  <div class="site-content">
      <div class="mdl-grid site-max-width">
        <div class="mdl-cell mdl-cell--12-col mdl-card mdl-shadow--4dp page-content">
          
          <div class="mdl-grid">
              <form action="{%url 'DataUpload' %}" method="POST" class="form-contact">
                {%csrf_token%}    
                </div>
                <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
                  {{form.file}}
                </div>
                  <button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" type="submit">
                  Submit
                  </button>
              </form>
            </div></div>
          </div>
        </div>
      </div>
    </div>

</div>

console log after submitting the form

Quit the server with CONTROL-C.
[22/Dec/2022 15:14:19] "POST /DataUpload HTTP/1.1" 200 1317

I'm not getting any error anywhere, but it's not uploading the file.

I fixed the issue and posted the solution here so that it won't trouble anyone else in the future.

The first thing I changed is I added enctype="multipart/form-data" to prevent a silent error invalid form issues.

      <form action="{%url 'DataUpload' %}" method="POST" enctype="multipart/form-data" class="form-contact">

Second, f is an object of some class in Django, so I just changed it to f.name

def handle_uploaded_file(f):
    with open(os.getcwd()+f.name, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

Finally, it worked perfectly. Thanks

Back to Top