好的,它不能是 lambda,因为 lambda 出于某种原因不可序列化,但这是简单的答案。
def pic_loc(instance, filename):
"""
:param instance: Product Instance
:param filename: name of image being uploaded
:return: image location for the upload
"""
return '/'.join([str(instance.pk), str(instance.slug), filename])
Class Product(models.Model):
image = models.ImageField(upload_to=pic_loc)
slug = models.SlugField()
user = models.ForeignKey(User, related_name="products")
然后找到说 pk = 1 :
slug = 'new-thing' 将是 //myexample.com/MEDIA_ROOT/1/new-thing/mything.png
<img src="{{ obj.image.url }}">
这是假设您已设置 MEDIA_ROOT,因为上传会转到媒体和媒体 url。像在生产环境中处理静态文件一样提供服务,以 MEDIA_URL 命名。
upload_to 将对象实例和文件名都传递给您的函数,您可以从那里操作它。
要更改实际文件名,您需要在 save() 方法中做一些额外的工作。
from django.core.files import File
class Product(models.Model):
label = CharField(max_length=255)
...
def save(self, **kwargs):
# here we use os.rename then change the name of the file
# add condition to do this, I suggest requerying the model
# and checking if label is different
if self.pk: # Need this to mitigate error using self.pk
if Product.objects.get(pk=self.pk).label != self.label:
path = self.image.path
rename = '/'.join(path.split('/')[:-1]) + '/' + self.label
os.rename(path, rename)
file = File(open(rename))
self.image.save(self.label, file)
return super(Product, self).save(**kwargs)
如果文件扩展名很重要,那么在创建标签时将其添加到标签中,或者我们将旧文件扩展名作为字符串的一部分:
filename, file_extention = os.splitext(path)
rename += file_extension # before renaming and add to label too
os.rename(path, rename)
self.image.save(self.label + file_extension, file)
我实际上建议编写一个重命名函数作为 app_label.utils 的一部分
检查文件是否存在很简单
if os.path.isfile(rename):
# you can also do this before renaming,
# maybe raise an error if the file already exists