Skip to content

Instantly share code, notes, and snippets.

@joshcartme
Last active December 11, 2015 06:39
Show Gist options
  • Save joshcartme/4561200 to your computer and use it in GitHub Desktop.
Save joshcartme/4561200 to your computer and use it in GitHub Desktop.
Middleware to enforce a sub directory of the media library is used based on the value associated with a host in the HOST_THEMES dictionary.
import os
from django.conf import settings
from django.http import HttpResponseRedirect
from filebrowser_safe.settings import DIRECTORY
class FilebrowserHostThemesDirectoryMiddleware(object):
"""
When in the media library redirect force the dir parameter to start
with the value specified for the host in the HOST_THEMES settigns. If
no value is specified do nothing.
"""
def process_request(self, request):
if request.path.startswith('/admin/media-library/') and \
not request.path.startswith('/admin/media-library/check_file') and \
not request.path.startswith('/admin/media-library/upload_file'):
host = request.get_host().split(":")[0].lower()
try:
dir_name = settings.HOST_THEMES[host]
except KeyError:
pass
else:
upload_path = request.GET.get('dir', '')
if not os.path.exists(os.path.join(settings.MEDIA_ROOT, DIRECTORY, dir_name)):
os.makedirs(os.path.join(settings.MEDIA_ROOT, DIRECTORY, dir_name))
if not upload_path.split('/')[0] == dir_name:
upload_path = '%s/%s' % (dir_name, upload_path)
upload_path = upload_path.strip('/')
if '?' in request.get_full_path():
url_char = '&'
else:
url_char = '?'
redirect_url = '%s%sdir=%s' % (request.get_full_path(), url_char, upload_path)
return HttpResponseRedirect(redirect_url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment