Menu Close

How to upload a file in Python Django?

To upload a file in Python Django, we can get the upload files from request.FILES.

For instance, we write

for key, file in request.FILES.items():
    path = file.name
    dest = open(path, 'w')
    if file.multiple_chunks:
        for c in file.chunks():
            dest.write(c)
    else:
        dest.write(file.read())
    dest.close()

to loop through the request.FILES dictionary in our view function.

And then we can write the files into disk with write.

We can add a simple upload form with

<form action="/upload_file/" method="post" enctype="multipart/form-data">
  {% csrf_token %}
  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" />
  <br />
  <input type="submit" name="submit" value="Submit" />
</form>

which has a file input.

The action attribute of the form is set to the URL of the file upload view.

Posted in Python, Python Answers