Python 为动态上传文件构建函数帮助器

Python 为动态上传文件构建函数帮助器,python,django,Python,Django,首先,我希望你们身体健康 嗨,我想让所有上传的文件都上传到与它的模型名相关的动态命名文件中 这是我创建的要放在imageField中upload_to=参数上的函数 def get_random_alphanumeric_string(length): letters_and_digits = string.ascii_letters + string.digits result_str = ''.join((random.choice(letters_and_digits) f

首先,我希望你们身体健康

嗨,我想让所有上传的文件都上传到与它的模型名相关的动态命名文件中

这是我创建的要放在imageField中upload_to=参数上的函数

def get_random_alphanumeric_string(length):
    letters_and_digits = string.ascii_letters + string.digits
    result_str = ''.join((random.choice(letters_and_digits) for i in range(length)))
    return result_str

def namefile_profile_picture(instance, filename):
    ext = filename.split('.')[-1]
    get_random_1 = get_random_alphanumeric_string(10)
    get_random_2 = get_random_alphanumeric_string(10)
    name_of_file = "{}{}{}".format(get_random_1,str(instance.id),get_random_2)
    filename = "%s.%s" % (name_of_file, ext)
    return 'user_{}/{}/{}'.format(instance.user.username,'profile_picture',filename)


def namefile_poster_picture(instance, filename):
    ext = filename.split('.')[-1]
    get_random_1 = get_random_alphanumeric_string(10)
    get_random_2 = get_random_alphanumeric_string(10)
    name_of_file = "{}{}{}".format(get_random_1,str(instance.id),get_random_2)
    filename = "%s.%s" % (name_of_file, ext)
    return 'user_{}/{}/{}'.format(instance.user.username,'poster_picture',filename)
    
def namefile_photo(instance, filename):
    ext = filename.split('.')[-1]
    get_random_1 = get_random_alphanumeric_string(10)
    get_random_2 = get_random_alphanumeric_string(10)
    name_of_file = "{}{}{}".format(get_random_1,str(instance.id),get_random_2)
    filename = "%s.%s" % (name_of_file, ext)
    return 'user_{}/{}/{}'.format(instance.user.username,'photo',filename)
    
因此,不要对每个不同的imageField手动使用这些函数 比如

我希望有一种方法可以创建这样一个函数或类来执行上面的示例

我可以轻松地将一些名称文件作为参数传递到一个函数中

我试着去查一下,我找到了一些方法,但似乎使用了非常古老的技术

他们都在使用@deconstructible decorator来创建帮助函数,但似乎decorator没有维护,或者是在django的旧版本中

让我知道是否有更好的方法来实现这一点

class Photo(models.Model)`:
    ...
    image = models.ImageField(upload_to=namefile_photo)
    ...

class Profile(models.Model):
    ...
    image = models.ImageField(upload_to=namefile_profile_picture)
    ...


class Profile(models.Model):
    ...
    image = models.ImageField(upload_to=namefile('profile'))
    ....