在Django中上传到FileField时保留文件名

时间:2018-06-21 16:06:54

标签: django django-models

在我的一个模型中,我有一个ImageField(基本上是FileField,但有一些额外的花絮)。我用以下内容指定上传位置:

class MyModel(models.Model):
    image = models.ImageField(blank=True, null=True, upload_to='path/to/directory'

将图像保存到此ImageField时,将使用以下内容:

with open(original_image.path) as image_file:
    image_temp = ContentFile(name=os.path.basename(original_image.path), content=image_file.read())
    my_model.image = image_temp

不幸的是,此操作将文件从原来的名称重命名为“目录”。现在这不是什么大问题,但是我需要保留图像的原始扩展名。如何保留原始文件扩展名?

1 个答案:

答案 0 :(得分:0)

根据我对您的问题的了解程度,尝试更改您的功能。

def upload_image_path(instance, filename):
    new_filename = random.randint(1,910209312) # or use whatever you want
    name, ext = get_filename_ext(filename)
    final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext)
    return "chapters/{new_filename}/{final_filename}".format(
            new_filename=new_filename, 
            final_filename=final_filename
            )# this will be your location


def get_filename_ext(filepath):
    base_name = os.path.basename(filepath)
    name, ext = os.path.splitext(base_name)
    return name, ext


  image = models.FileField(upload_to = upload_image_path, null = True, blank = True)

希望这会很好。