Last active
December 11, 2015 06:39
-
-
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.
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
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