Django static files

Prerequisites

Static Files

  • Static files are files that do not change based on user interaction.
  • These include stylesheets (CSS), JavaScript files (JS), images (e.g., PNG, JPEG), and other client-side resources like fonts.
  • Unlike dynamically generated content (such as HTML pages generated by Django views), static files are served as-is to the client.

Configure static files in settings

  • To properly serve static files, Django requires a few settings in our settings.py file.

  • STATIC_URL: It defines how our static files will be referenced in our HTML templates.

  • STATICFILES_DIRS: It's the list of directories which are used by the django to look for static files.
  • STATIC_ROOT: It's the directory where all static files are copied to when the command python manage.py collectstatic is executed.
  • Add the static settings to the project like below.

my_project/settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / "static",]
STATIC_ROOT = BASE_DIR / "staticfiles"

Adding static files to project

  • Static files can be stored in two primary locations:

    • Per App Static Folder: Each Django app can have its own static directory. Django will automatically look in each app's static/ subdirectory.
    • Global Static Folder: we can also store static files in a global static directory outside of apps (this is defined by STATICFILES_DIRS).
  • Create static file static/global_styles.css and add below css.

static/global_styles.css

body {
  background: yellow;
  color: black;
  font-size: 14px;
}
  • Create static file static/global_script.js and add below javascript to it.
const button = document.createElement("input");
button.setAttribute("type", "submit");
button.setAttribute("value", "Click me");
document.body.appendChild(button);
button.addEventListener("click", function () {
  alert("Hey! User");
});
.
├── manage.py
├── my_app
│   └── static
│       └── my_app
│           ├── app_styles.css
│           └── app_script.js
├── my_project
└── static
        ├── global_styles.css
        └── global_script.js

Using Static Files in Templates

  • To reference static files in Django templates, we must first load the static template tag at the beginning of our template.
  • Once loaded, we can refer to static files using the static tag.

  • Open template templates/home.html and below code to it.

templates/home.html

{% load static %}
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="{% static 'global_styles.css' %}">
  </head>
  <body>
    <h1>Hello, {{ request.user.username }}</h1>
    <p>You logged in</p>
    <script src="{% static 'global_script.js' %}"></script>
  </body>
</html>

Serving Static Files During Development

  • In development, Django serves static files automatically when you run the development server using python manage.py runserver
  • No need of any special configurations or tools during development, as Django handles static files automatically through its lightweight development server.

Collecting Static Files for Production

  • When we deploy your Django project, static files need to be collected into one directory, typically defined by STATIC_ROOT
  • These files can be copied to STATIC_ROOT directory using command python manage.py collectstatic
  • Django will look through each app’s static/ directory and any locations defined in STATICFILES_DIRS, and then copy all static files into STATIC_ROOT.

Note: In production, Django doesn’t serve static files automatically. You will need a web server like Nginx or Apache to serve static content efficiently.

Best Practices for Static Files Management

  • Organize by App: Place static files related to each app inside that app’s static directory to maintain structure and avoid conflicts.
  • Use a CDN: For faster loading times and optimized delivery, consider hosting your static files on a Content Delivery Network (CDN) like AWS S3 or Cloudflare.
  • Minify Assets: Minify CSS and JavaScript files before deployment to reduce file size and improve performance.
  • Versioning: Use version control on static files (like appending a version number to filenames) to avoid browser caching issues when deploying updates.

Testing the static files

  • Run the development server using command python manage.py runserver
  • Open brower and access http://127.0.0.1:8000/home/
  • Now, we can observe that the page background is yellow.
  • We can also find button with title Click me and when clicked it will show alert saying Hey! User
  • If it works like mentioned above then we can confirm static files are loaded by the app.