我有一个带有图像域的表单,我想给图像赋予唯一的名称,以避免覆盖我怎样才能实现?
models.py
class Payment(models.Model):
Address = models.CharField(max_length=255)
Payment_ID = models.ImageField(upload_to='pay_proof/')
Status = models.CharField(max_length=5, default="X")
Review_result = models.CharField(max_length=255, default="Not yet reviewed")
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created']
def __unicode__(self):
return u'%s'% self.Status
def __str__(self):
return self.Status
答案 0 :(得分:1)
覆盖save
方法并提供您想要的图像文件名称。
def uniqueimage(name):
image_name = "Logic to uniquely name the image"
return image_name
class Payment(models.Model):
Address = models.CharField(max_length=255)
Payment_ID = models.ImageField(upload_to='pay_proof/')
Status = models.CharField(max_length=5, default="X")
Review_result = models.CharField(max_length=255, default="Not yet reviewed")
created = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kargs):
if self.Payment_ID:
self.Payment_ID.name = uniqueimage(str(self.Payment_ID.name))
super(Payment, self).save(*args, **kwargs)
注意:请注意,使用.update
方法直接更新字段时,此功能无效。