Django: Configure and connect to static files

How to configure Django to connect to our static files.


What are static files?

Simply put, static files consist of CSS, JavaScript and any media files such as images. They are known as "static" because they aren't server-generated, and hence not dynamic.


So, let's get started

...


Step 1:

Make sure that you create a static folder in your root/base directory, like so:


# - Base/Root directory 

MyProject
---> MyProject (contains settings.py)
---> MyApp
---> static
---> templates
---> venv
---> db.sqlite3
---> manage.py


Step 2:

Ensure that there that STATIC_URL is setup in settings.py:


# - settings.py

STATIC_URL = 'static/'


Step 3:

Configure Django to connect to our static folder.


In the code below, we are telling Django to look into our base directory and then to look for the static folder. After finding the static folder we are then saying that we want to bridge a connection


# - settings.py

import os

# --------- Older way to configure -------- #

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


# --------- Newer way to configure -------- #

STATICFILES_DIRS = [BASE_DIR / 'static']


As you can see there are two ways to configure Django to connect to our static folder. So, whether you are using an older or a newer version of Django, you are covered either way.