Skip to content

Instantly share code, notes, and snippets.

@luzfcb
Forked from specialunderwear/staticfiles.py
Created November 24, 2011 12:28
Show Gist options
  • Save luzfcb/1391246 to your computer and use it in GitHub Desktop.
Save luzfcb/1391246 to your computer and use it in GitHub Desktop.
Use django collectstatic with apps that have 'media' folders instead of 'static' folders. Also make run server serve files in the MEDIA_ROOT automatically, even if it is inside STATIC_ROOT.
import os
from django.conf import settings
from django.contrib.staticfiles.finders import BaseFinder, AppDirectoriesFinder
from django.contrib.staticfiles.storage import AppStaticStorage
from django.core.files.storage import FileSystemStorage
from django.utils._os import safe_join
class AppMediaStorage(AppStaticStorage):
source_dir = 'media'
class MediaFinder(AppDirectoriesFinder):
storage_class = AppMediaStorage
class MediaRootFinder(BaseFinder):
"""
Since the static files runserver can not find media definitions, it is now
added by this finder. This way you don't have to define anything in urls.py
to make django server both static and media files.
"""
def find(self, path, all=False):
"""
Looks for files in the MEDIA_ROOT
"""
media_prefix = settings.MEDIA_URL.replace(settings.STATIC_URL, '')
if path.startswith(media_prefix):
location = safe_join(settings.STATIC_ROOT, path)
if os.path.exists(location):
if not all:
return location
return [location]
return []
def list(self, ignore_patterns):
"""
List all files in all locations.
"""
yield settings.MEDIA_ROOT, FileSystemStorage()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment