Created
June 20, 2022 15:50
-
-
Save augustomen/3e6e74a9b247244eca08216886308de3 to your computer and use it in GitHub Desktop.
Django - Render static links using CDN from GitHub
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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