Home » Django File Upload

Django File Upload

by Online Tutorials Library

Django File Upload

File upload to the server using Django is a very easy task. Django provides built-in library and methods that help to upload a file to the server.

The forms.FileField() method is used to create a file input and submit the file to the server. While working with files, make sure the HTML form tag contains enctype=”multipart/form-data” property.

Let’s see an example of uploading a file to the server. This example contains the following files.

Template (index.html)

It will create an HTML form which contains a file input component.

Form (forms.py)

View (views.py)

Here, one extra parameter request.FILES is required in the constructor. This argument contains the uploaded file instance.

Specify URL (urls.py)

Upload Script (functions.py)

This function is used to read the uploaded file and store at provided location. Put this code into the functions.py file. But first create this file into the project.

Now, create a directory upload to store the uploaded file. Our project structure looks like below.

django file upload

Initially, this directory is empty. so, let’s upload a file to it and later on it will contain the uploaded file.

Start Server

Output

django file upload 1

Submit this form and see the upload folder. Now, it contains the uploaded file.

django file upload 2

You may also like