Django Static Files in Local

Posted 3 years, 6 months ago
Views 510
2 min read
2 reactions

There are two types of files which interacts with our website.

  1. Media Files: Files uploaded by the users of our website.
  2. Static Files: Assets that our websiite needs for it to be presentable. E.g. Images, CSS , JS files etc.

In production we serve static files using NGINX, Whitenoise or other servers but In local / development stage django can elegantly handle static files. For production it is not recommended to serve static files using Django because it will be too slow and its not secure.

Lets jump straight into serving static files. For that we need to understand some of the terminologies first:

STATIC_URL: The url through which static files will be served. e.g if STATIC_URL = "/static/" files will be served from
STATIC_DIRS: Django looks for static files inside of each app in a folder named static. But there are static files which do not belong to any particular app. Or it might be the case that we don't want to make a folder named static inside of each app. In these two cases we define a STATIC_DIR where we keep our static files.
STATIC_ROOT: In development server this is useless. But in production server we use NGINX, Whitenoise etc. What they so is to serve the static files in production. This also makes it minimize the workload of Django in production. Hey but they don't know about our static files, So, how will they serve ? We run a command -> "python collectstatic". Now Django will look for all the static files and copy then to a location which we give as static root. Generaly it is AWS S3 or some other cloud storage. NGINX,whitenoise fetches the static files from this static root and will serve in production.
Now, lets configure our local settings.
Add the following lines in your local settings file

STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR/"static_dir"]  #using pathlib for Django 3.1+
# STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_dir')] #using os module for <3.1

Serving Static Images: Lets try to render an image at homepage. Django will search for static file in /static/ and static_dir folder. Lets put these lines in template.

{% load static %}
<img src="{% static 'images_here/firstimg.png' %}" style="width: 400px;">

Serving Static CSS: Put the css file at:

    color: rgb(18, 102, 39);
    box-shadow: 3px;

    color: blueviolet;

and put the below lines at template article_list.html

{% load static %}

<link rel="stylesheet" href="{% static 'blog/css/list.css' %}">

Serving Static Javascript Files: Put the following contents in static_dir/blog/js/background.js

    function () {
      var randomColor = Math.floor(Math.random()*16777215).toString(16); = "#"+randomColor;

and in the template we have to add these lines

{% load static %}
<script src="{% static 'blog/js/background.js' %}"></script>

2 reactions


Joined on May 29, 2020

Latest Videos