【发布时间】:2015-08-24 19:41:00
【问题描述】:
我有以下代码,models.py:
class Location(models.Model):
image_file = models.ImageField(upload_to=upload_to_location, null=True, blank=True)
name = models.CharField(max_length=200)
调用upload_to 函数,图像被重命名。然后我的保存方法
def save(self, *args, **kwargs):
try:
this = Location.objects.get(id=self.id)
if this.image_file:
os.remove(this.image_file.path)
except ObjectDoesNotExist:
pass
super(Location, self).save(*args, **kwargs)
try:
this = Location.objects.get(id=self.id)
if this.image_file:
resize(this.image_file.path)
except ObjectDoesNotExist:
pass
def upload_to_location(instance, filename):
blocks = filename.split('.')
ext = blocks[-1]
filename = "%s.%s" % (instance.name.replace(" ", "-"), ext)
return filename
检查以前上传的文件是否存在,如果存在,则将其删除。然后在保存后,它会再次检查文件是否存在,然后调用resize 函数。如果我上传文件并单击保存,那就行了。但是,如果我只更改位置的名称,则会调用 os.remove 函数,删除我的文件,然后 resize 函数会出错。
因此,我只想在用户上传upload_to 时调用os.remove 函数。
所以我尝试了几件事,但无法完成。我还尝试了pre_save 和post_save 信号。因此,我在获取图像路径时遇到了问题:
@receiver(pre_save, sender=Company)
def my_function2(sender, instance, **kwargs):
print instance.path #didn't work
print os.path.realpath(instance) #didn't work
有谁知道我如何使用pre_save 或其他方法解决这个问题?
【问题讨论】:
-
您是否阅读/考虑过实施custom upload handler 以满足您的需求?关于如何做到这一点的另一个可能的提示here
-
你写过
upload_to参数的自定义函数吗? -
是的,我做到了,我更新了我的问题,所以在
upload_to_location中的名称将被更改
标签: python django save image-uploading