Last active
March 21, 2018 05:54
-
-
Save Keda87/020754241ce0b3cfcdfe379bee36f082 to your computer and use it in GitHub Desktop.
Django model mixin class to extends django-storages (https://github.com/jschneier/django-storages) ability to backup media files to local storage.
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.core.files import File | |
from django.core.files.storage import FileSystemStorage | |
class LocalMediaSaveMixin(object): | |
"""Mixin class to for backing up media files on model that has | |
image/file fields. To use it, ensure to keep in my python multiple | |
inheritance order. The top most hierarchy must be on the most right. | |
example: | |
class MyModel(LocalMediaSaveMixin, models.Model): | |
pass | |
""" | |
def __init__(self, *args, **kwargs): | |
super(LocalMediaSaveMixin, self).__init__(*args, **kwargs) | |
# Setup django local file system storage. | |
self.storage = FileSystemStorage() | |
self.storage.base_location = settings.MEDIA_ROOT | |
self.media_fields = [ | |
i for i in self._meta.fields | |
if i.__class__.__name__ in ['ImageField', 'FileField'] | |
] | |
def save(self, *args, **kwargs): | |
"""Save media file (Image, File) to local storage.""" | |
from product.models import file_path # This import was from function that use to define path location and used on `upload_to=` | |
super(LocalMediaSaveMixin, self).save(*args, **kwargs) | |
# Getting file or image fields. | |
for field in self.media_fields: | |
raw_file = getattr(self, field.name) | |
file_name = os.path.split(raw_file.name)[1] | |
django_file = File(raw_file, file_name) | |
root, _ = os.path.split(file_path(None, file_name)) | |
root = root.replace('static/', '') | |
# Ensure the file is not exists. | |
if not os.path.isfile(os.path.join(settings.MEDIA_ROOT, root, file_name)): | |
self.storage.location = os.path.join(settings.MEDIA_ROOT, root) | |
self.storage.save(file_name, django_file) | |
@property | |
def local_media(self): | |
"""Listed all local media directory.""" | |
media = {} | |
for i in self.media_fields: | |
raw_file = getattr(self, i.name) | |
media[i.name] = os.path.join(settings.MEDIA_ROOT, raw_file.name.replace('static/', '')) | |
return media |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment