Django Upload File

Adi Ramadhan
2 min readOct 8, 2020

--

Simple Django upload file
Official doc here.

Simple upload file

Step 1: Preparation, Create Django Project, Initial Migration
create virtualenv: virtualenv venv
start virtualenv: venv/Scripts/activate
install Django in virtualenv: pip install django==3.0
Create Django: django-admin startproject myproject
Go to myproject folder: cd myproject
Initial Migration: python manage.py migrate

Step 2: Create Django Apps
Create apps: python manage.py startapp myapp
Add myapp to INSTALLED_APPS in myproject/settings.py

Step 3: Set up Templates Folder
Create folder templates in myapp

Add template directory in TEMPLATES parameter in myproject/settings.py

os.path.join(BASE_DIR, 'myapp', 'templates')

Step 5: Create HTML Files in myapp/templates Folder
create home.html

myapp/templates/home.html

Step 6: Create Function in Views.py
create home method in views.py

myapp/views.py

Step 7: Setup Media Folder
create myapp/media folder

myapp/media

set media url and media root in settings.py

MEDIA_URL = '/media/' #newMEDIA_ROOT = os.path.join(BASE_DIR, 'myapp', 'media') #new

Step 8: Setup URLs in myapp and myproject Folder
Create myapp/urls.py

myapp/urls.py

Update myproject/urls.py

myproject/urls.py

Step 9: Run Server and Testing
Run Server: python manage.py runserver
Testing: http://127.0.0.1:8000/

home
upload file
upload file success
uploaded file to media folder
File access via url (for image file will be show in folder, some format will be auto-downloaded)

--

--