如果您在迁移时遇到问题,则可能应该使用@deconstructible
装饰器。
import datetime
import os
import unicodedata
from django.core.files.storage import default_storage
from django.utils.deconstruct import deconstructible
from django.utils.encoding import force_text, force_str
@deconstructible
class UploadToPath(object):
def __init__(self, upload_to):
self.upload_to = upload_to
def __call__(self, instance, filename):
return self.generate_filename(filename)
def get_directory_name(self):
return os.path.normpath(force_text(datetime.datetime.now().strftime(force_str(self.upload_to))))
def get_filename(self, filename):
filename = default_storage.get_valid_name(os.path.basename(filename))
filename = force_text(filename)
filename = unicodedata.normalize('NFKD', filename).encode('ascii', 'ignore').decode('ascii')
return os.path.normpath(filename)
def generate_filename(self, filename):
return os.path.join(self.get_directory_name(), self.get_filename(filename))
用法:
class MyModel(models.Model):
file = models.FileField(upload_to=UploadToPath('files/%Y/%m/%d'), max_length=255)