# # -*- coding: utf-8 -*- # from __future__ import unicode_literals # # Erik Stein , 2016 import os import uuid from django.conf import settings from django.db import models # TODO Use improved slugify from django.utils.text import slugify class UUIDMixin(models.Model): uuid_hex = models.CharField(max_length=32, null=False, editable=False) class Meta: abstract = True # TODO Make auto-initializing UUID-field def get_uuid(self): if not self.uuid_hex: self.uuid_hex = uuid.uuid4().hex return str(uuid.UUID(self.uuid_hex)) def get_upload_path(instance, filename, storage): """ Returns //original/. where - uuid and name are fields from instance, - filename is slugified and shortened to a max length including the extension. - extension is preserved from original filename """ name, ext = os.path.splitext(filename) name = slugify(name) name = name[:(storage.FILENAME_MAX_LENGTH - len(ext))] filename = "%s%s" % (name, ext) return os.path.join( instance.get_uuid(), instance.storage.ORIGINAL_FILE_PREFIX, filename )