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:

from django.apps import AppConfig


class UploadConfig(AppConfig):
    name = 'upload'

Open settings.py, find INSTALLED_APPS, then add:

INSTALLED_APPS = [
    ...
    'upload.apps.UploadConfig',
]

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.

MEDIA_ROOT = os.path.join(BASE_DIR, 'files')
MEDIA_URL = '/files/'

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:

from django.shortcuts import render
from django.core.files.storage import FileSystemStorage
  
def upload(request):
    context = {}
    
    if request.method == 'POST':
        uploadFile = request.FILES['file']      
        fs = FileSystemStorage()
        name = fs.save(uploadFile.name, uploadFile)
        context['url'] = fs.url(name)
    return render(request, 'upload.html', context)

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:

ozenero UploadFile

{% csrf_token %}
{% if url %} Upload completely:
{{ url }} {% endif %}

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':

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        ...
    },
]

Set Url pattern

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

urls.py

from django.urls import path
from django.conf import settings
from django.conf.urls.static import static

from upload import views

urlpatterns = [
    path('upload/', views.upload, name='upload'),
]

if settings.DEBUG: # remember to set 'DEBUG = True' in settings.py
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Source Code

DjangoUploadFiles

0 0 votes
Article Rating
Subscribe
Notify of
guest
1.3K Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments