我正在尝试从图像创建裁剪图像并将它们保存在两个单独的模型中。我可以上传并保存整个图像。我在Crop模块中有一个函数,用于在创建时将随机字符串指定为文件名。当我使用管理界面创建一个Crop对象时,这很好用。但是,如果我在视图中使用shell或只是脚本,则会创建裁剪但不会保存到正确的位置。
Models.py:
def changeName(instance, filename):
print ("SOMETHING")
ext = filename.split('.')[-1]
filename = "%s.%s" % (name_generator(), ext)
print filename
return os.path.join('croppedImages/', filename)
def name_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
class Image(models.Model):
wholeImage = models.ImageField(upload_to = 'wholeImages/')
level = models.IntegerField(default = 1)
answer = models.CharField(max_length =200)
def save(self):
if not self.id and not self.wholeImage:
return
super(Image,self).save()
image = Im.open(self.wholeImage)
image=image.resize((500,600),Im.ANTIALIAS)
image.save(self.wholeImage.path)
class Crop(models.Model):
image = models.ForeignKey(Image)
croppedImage = models.ImageField(upload_to=changeName)
position_x = models.IntegerField()
position_y = models.IntegerField()