Django ImageField上载更改文件名 [英] Django ImageField change file name on upload

查看:449
本文介绍了Django ImageField上载更改文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在保存模型产品后,我希望将上传的图片命名为与pk相同的名称,例如22.png或34.gif。我不想更改图片的格式,而只是更改名称。如何才能做到这一点?到目前为止,我的模型示例...

Upon saving me model 'Products' I would like the uploaded image to be named the same as the pk for example 22.png or 34.gif I don't want to change the format of the image just the name. How can this be done? example of my model so far below...

image = models.ImageField(
        upload_to="profiles",
        height_field="image_height",
        width_field="image_width",
        null=True,
        blank=True,
        editable=True,
        help_text="Profile Picture",
        verbose_name="Profile Picture"
    )
    image_height = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")
    image_width = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")


推荐答案

您可以将函数传递到 upload_to 字段中:

You can pass a function into upload_to field:

def f(instance, filename):
    ext = filename.split('.')[-1]
    if instance.pk:
        return '{}.{}'.format(instance.pk, ext)
    else:
        pass
        # do something if pk is not there yet

我的建议是返回一个随机文件名而不是 {pk}。{ext} 。另外,它会更安全。

My suggestions would be to return a random filename instead of {pk}.{ext}. As a bonus, it will be more secure.

发生的事情是Django将调用此函数来确定文件应上传到的位置。这意味着您的函数负责返回文件的整个路径,包括文件名。以下是修改后的函数,您可以在其中指定上传到何处以及如何使用它:

What happens is that Django will call this function to determine where the file should be uploaded to. That means that your function is responsible for returning the whole path of the file including the filename. Below is modified function where you can specify where to upload to and how to use it:

import os
from uuid import uuid4

def path_and_rename(path):
    def wrapper(instance, filename):
        ext = filename.split('.')[-1]
        # get filename
        if instance.pk:
            filename = '{}.{}'.format(instance.pk, ext)
        else:
            # set filename as random string
            filename = '{}.{}'.format(uuid4().hex, ext)
        # return the whole path to the file
        return os.path.join(path, filename)
    return wrapper

FileField(upload_to=path_and_rename('upload/here/'), ...)

这篇关于Django ImageField上载更改文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆