Using Static Files in Django
Let's learn how to serve a static image.
So far, we have used templates to insert simple text. But we don’t always just want text. Sometimes, we want to send other types of media, too. For example, say we wanted to return a user’s photo. For this kind of purpose, we use static files.
What are static files?
Static files are files that clients download as they are from the server or files that get served statically, i.e. with no modification. These static files could include stylesheets, JavaScript files, and images. Now, let’s see how to serve static files.
For this example, we will be using the code we got from the Code Templates in Django lesson.
We need to perform the following steps:
Step 1: Create a static
directory
First, we will create a directory by the name of static in the outermost first_project directory. Inside this directory, we will create a first_app directory, just like we did with templates. Then, we have to create another directory, and call it images. So, the folder hierarchy becomes: first_project/static/first_app/images/
.
Step 2: Tell Django where to find static images
In this step, we edit the settings.py
file, just like we did with templates. We begin by opening the settings.py
file. As we did with templates, we will use os.path.join
to specify the static directory. So, we add the following line below the TEMPLATE_DIR
line:
STATIC_DIR = os.path.join(BASE_DIR,"static")
In the above example, the STATIC_DIR
variable holds the absolute path to the location of the static
folder inside of our project. Now, scroll all the way down in the settings.py
file and we will notice a pre-built variable by the name of STATIC_URL
holding a value of /static/
. However, we want to add another variable that will be able to take a list of static file directory paths. The reason for this is that when dealing with our own applications and projects, we want to take the same approach we did with templates and give each application its own special folder. Within that folder is where we put the images
. So, that’s what we did in Step 1. Add the following line below the STATIC_URL
line:
STATICFILES_DIRS = [
STATIC_DIR,
]
In this example, STATICFILE_DIRS
holds the list of static file directories.
Get hands-on with 1400+ tech skills courses.