Static Assets in Django
- Configure Static Files in settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / "static"]
In your Django app, create a "static" directory.
Structure your static files within the "static" directory based on their purpose.
Load the static template tag in your HTML file:
{% load static %}
- Reference static files using the {% static %} template tag:
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
- Run the collectstatic management command to gather static files from all apps into a single location:
python manage.py collectstatic
Configure a web server or use Django's development server to serve static files in production.
In production, consider using a Content Delivery Network (CDN) for improved performance.
Use the Whitenoise middleware for simplified static file serving in production (optional).
MIDDLEWARE = [
# ...
'whitenoise.middleware.WhiteNoiseMiddleware',
# ...
]
- Install the Whitenoise package (if using it):
pip install whitenoise