Static files are assets like JavaScript files, CSS stylesheets, and images that are part of your application’s frontend but are not generated dynamically. Django makes it easy to serve static files in both development and production environments.
Configuring Static Files in Django
Django automatically handles static files during development, but you need to configure settings for both the development and production environments.
Basic Configuration:
In settings.py
, Django provides the STATIC_URL
setting to define the URL where static files are served. By default, Django uses a directory named static/
to store all static files in your project.
STATIC_URL
: This is the URL to access the static files (e.g.,/static/
).STATICFILES_DIRS
: This is a list of directories where Django will look for additional static files during development.STATIC_ROOT
: This is the absolute path to the directory where all static files will be collected when you runcollectstatic
for production. It is empty by default.
Example of Static File in Django Template:
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">
<script src="{% static 'js/app.js' %}"></script>
Serving Static Files in Development
When you’re running the Django development server (python manage.py runserver
), Django automatically serves static files. There is no need for additional configuration for static files in development.
However, in production, static files should not be served by Django itself. Instead, a web server (e.g., Nginx, Apache) should serve these files for better performance.