Django Load Image from Static Directory

Adi Ramadhan
2 min readAug 3, 2020

--

Basic usage of load static images.

home.html

Read official docs here.

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

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 4: Set up Static Folder (images, css, js)
Create static folder inside myapp. Static folder contains css, images and js folder

Add STATICFILES_DIRS in myproject/settings.py

STATICFILES_DIRS = [os.path.join(BASE_DIR,'myapp/static'),]

Step 5: Create HTML File with Image Loaded
Add an image in myapp/static/images. Example: cat.jpg

Create home.html file in myapp/templates.

home.html

Step 6: Create Class Based View
Create view method in myapp/views.py

myapp/views.py

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

myapp/urls.py

Update myproject/urls.py

myproject/urls.py

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

--

--