Skip to content

Instantly share code, notes, and snippets.

@augustomen
Created June 20, 2022 15:50
Show Gist options
  • Save augustomen/3e6e74a9b247244eca08216886308de3 to your computer and use it in GitHub Desktop.
Save augustomen/3e6e74a9b247244eca08216886308de3 to your computer and use it in GitHub Desktop.
Django - Render static links using CDN from GitHub
from urllib.parse import urljoin
from django.conf import settings
from django.contrib.staticfiles.storage import StaticFilesStorage
from django.utils.encoding import filepath_to_uri
class CustomStaticFilesStorage(StaticFilesStorage):
"""Allows setting a different STATIC_URL for each static file prefix."""
def url(self, name):
for prefix, base_url in settings.STATIC_URL_RULES:
if name.startswith(prefix):
# largely based on django.core.files.storage.FileSystemStorage
url = filepath_to_uri(name)
if url is not None:
url = url.lstrip('/')
return urljoin(base_url, url)
return super().url(name)
# Add these settings to your settings.py file:
STATICFILES_STORAGE = 'cdn_storage.CustomStaticFilesStorage'
STATIC_URL_RULES = [
('admin/', f'https://cdn.statically.io/gh/django/django/{django.__version__}/django/contrib/admin/static/'),
]
# All other paths:
STATIC_URL = '/static/'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment