0
在我的项目中,用户可以上传图像,一旦保存,我可以运行post_save信号以使用Pillow修改图像。修改图像后,我需要用新图像替换现有的图像。现在的问题是,如果我在post_save信号中运行保存方法,它会导致最大的递归错误。所以,我正在考虑使用更新方法但会引发文件中字符的错误。如何使用新图像更新Django模型中的ImageField
下面是代码:
def menuImageLocation(instance,filename):
return "%s/%s"%(instance,filename)
class restaurantMenuImage(models.Model):
restaurant = models.ForeignKey(restaurantCreateUpdate)
title = models.CharField(max_length=100,null=True,blank=True)
menuImage = models.ImageField(upload_to=menuImageLocation,null=True,blank=True,verbose_name="Menu Image")
def __unicode__(self):
return str(self.restaurant)
@receiver(post_save,sender=restaurantMenuImage)
def modifyMenuImage(sender,instance,**kwargs):
getRestaurant = restaurantCreateUpdate.objects.get(restaurantName=instance.restaurant)
image_path = instance.menuImage.path
filename = os.path.basename(image_path)
image_hold = Image.open(image_path)
image = image_hold.resize((300,300),Image.ANTIALIAS)
temp_loc = "%s/%s/%s/tmp"%(settings.MEDIA_ROOT,"menu",getRestaurant.uniqueID)
if not os.path.exists(temp_loc):
os.makedirs(temp_loc)
temp_file_path = os.path.join(temp_loc,filename)
if os.path.exists(temp_file_path):
temp_path = os.path.join(temp_loc,"%s" %(random.random()))
os.makedirs(temp_path)
temp_file_path = os.path.join(temp_path,filename)
temp_image = open(temp_file_path,"w")
image.save(temp_image,quality=80)
temp_data = open(temp_file_path,"r")
image_file = File(temp_data)
instance.menuImage.save(filename, image_file)
所以,如果我运行代码的最后一行,这将导致到最大递归误差,而不是使用保存方法,我尝试使用更新文件的方法路径,但为此我得到的错误,字符超过了“image_file”的max_length。请感谢任何帮助。
感谢先进!