gpt4 book ai didi

django - 如何在上传文件/图片的名称中使用主键id?

转载 作者:行者123 更新时间:2023-12-02 06:45:36 24 4
gpt4 key购买 nike

我需要生成带 mask 的上传图片的名称

images/{{ uploaded_image.id }}.jpg

我认为最好的方法是 FileField.upload_to 属性,但它写成 Here :

In most cases, this object will not have been saved to the database yet, so if it uses the default AutoField, it might not yet have a value for its primary key field.

在我的情况下,在 save() 方法中保存对象后重命名文件可能会更好?

最佳答案

我做的是给 upload_to 一个函数,然后分配一个 UUID 是它保存到的函数:

import uuid

def get_upload_to(instance, filename):
instance.uuid = uuid.uuid4().hex
return 'blah/%s/%s' % (instance.uuid, filename)

class Photo(models.Model):
file = models.FileField(max_length=200,upload_to=get_upload_to)
uuid = models.CharField(max_length=32)

关于django - 如何在上传文件/图片的名称中使用主键id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1024561/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com