Static Assets in Django

  1. Configure Static Files in settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / "static"]
  1. In your Django app, create a "static" directory.

  2. Structure your static files within the "static" directory based on their purpose.

  3. Load the static template tag in your HTML file:

{% load static %}
  1. Reference static files using the {% static %} template tag:
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
  1. Run the collectstatic management command to gather static files from all apps into a single location:
python manage.py collectstatic
  1. Configure a web server or use Django's development server to serve static files in production.

  2. In production, consider using a Content Delivery Network (CDN) for improved performance.

  3. Use the Whitenoise middleware for simplified static file serving in production (optional).

MIDDLEWARE = [
    # ...
    'whitenoise.middleware.WhiteNoiseMiddleware',
    # ...
]
  1. Install the Whitenoise package (if using it):
pip install whitenoise