Django – How to upload file

django-upload-file-example-project-structure-feature-image

In this tutorial, we’re gonna look at a simple way to upload file in Django Application.

Related Post: Django – How to upload, view, delete file using ModelForm and MySQL

Overview

Goal

django-upload-file-example-overview

We will create build a simple Django Project that has UI for user to choose file to upload.
After the uploading completely, it shows the url to the file.
The uploaded file will be stored in local storage.

Project Structure

django-upload-file-example-project-structure

settings.py contains settings for media path.
urls.py with urlpatterns (including /upload path to views)
upload/views.py defines upload() function to handle HTTP POST request.
templates/upload.html is the template for upload form corresponding to /upload url.
files folder is the directory that contains all uploaded files.

Implement Django project

Setup Project

Create Django project named DjangoUploadFiles with command:
django-admin startproject DjangoUploadFiles

Run following commands to create new Django App named upload inside the project:
cd DjangoUploadFiles
python manage.py startapp upload

Open upload/apps.py, we can see UploadConfig class (subclass of the django.apps.AppConfig) that represents our Django app and its configuration:

Open settings.py, find INSTALLED_APPS, then add:

Configure path for uploaded files

In project’s settings.py, set value for MEDIA_ROOT and MEDIA_URL:
+ MEDIA_ROOT: Absolute filesystem path to the directory that holds uploaded files.
+ MEDIA_URL: url for media (uploaded files) from MEDIA_ROOT.

So uploaded files will be accessed with url /files/file_name, and they are located at folder named files.

Handle Upload File request

Inside upload/views.py, define upload() function:

File from HTTP request is stored as request.FILES[] which is a dictionary-like object. Each key in request.FILES[] is the name from the <input type="file" name="key" /> in HTML template. Each value in request.FILES is an UploadedFile instance.

Add template for uploading file

Create template with form submission

Under project root folder, create templates folder, then create upload.html file insides:

The form is submitted via POST method, and the submitted file will be placed in request.FILES.

We must use the attribute enctype="multipart/form-data" in HTML form. If not, request.FILES in views.upload(request) will be empty.

We also show the uploaded file’s url of context parameter returned from views.upload() function.

Specify template directory

In project’s settings.py, set templates path for 'DIRS':

Set Url pattern

Now, we add path to urlpatterns and set up location for uploaded files:

urls.py

Source Code

DjangoUploadFiles

By grokonez | March 10, 2019.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*