只是一個字段這是我的models.py:Overiding節省在Django
class College(models.Model):
name = models.CharField(unique=True, max_length=50,
help_text='Name of the college.'
)
slug = models.SlugField(unique=True)
description = models.TextField(blank = True)
image = models.ImageField(upload_to='site-media/media/college_images/',
default = 'site-media/media/college_images/default.jpeg'
)
user = models.ForeignKey(User)
def get_absolute_url(self):
return "/%s/" % self.slug
def create_thumbnail(self):
if not self.image:
return
THUMBNAIL_SIZE = (250,193)
image = Image.open(StringIO(self.image.read()))
thumb = ImageOps.fit(image, THUMBNAIL_SIZE, Image.ANTIALIAS)
temp_handle = StringIO()
thumb.convert('RGB').save(temp_handle, 'jpeg')
temp_handle.seek(0)
suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
temp_handle.read(), content_type='image/jpeg')
self.image.save('%s_college_.%s'%(os.path.splitext(suf.name)[0],'jpeg'), suf, save=False)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
self.create_thumbnail()
super(College, self).save(*args, **kwargs)
我已經呈現給用戶一個表單編輯只是描述。當描述'POST'被創建時,上面的'save()'方法被調用。問題在於縮略圖每次都會以一個更大的名字反覆創建。而且,前一個縮略圖也不會從硬盤上刪除。是否有可能,這個'縮略圖'方法在'description'的每個編輯中都不會被反覆調用。
從'save'中重新創建'create_thumbnail'並在需要時手動調用它有什麼問題嗎? – kalhartt
以及我沒有嘗試,因爲我希望每次創建College實例時都要調用它。 – toothie
當你保存一個新的'College'實例時,你只想調用'create_thumbnail'嗎? –