Django overwrite save
I'd like to overwrite save method in my model to create proper slug and create copy of imagefield with small modifications in it. How can I handle with that?
def save(self, *args, **kwargs):
super(MyModel, self).save(*args, **kwargs) #to get id
#slug
se开发者_如何转开发lf.slug = '%s-%i' % (self.topic, self.id)
#create copy of img
cp_path = dirname(self.image.path)+'/copies_'+basename(self.image.path)
shutil.copy2(self.image.path, cp_path)
file = open(cp_path)
django_file = File(file)
django_file.name = basename(cp_path) #otherwise path will be duplicated
self.cp_image = django_file
super(MyModel, self).save(*args, **kwargs) #to save my new ImageField
create_watermark(self.cp_image, self.topic, self.text, 500, 45)
Cause I use super(MyModel, self).save() twice I've got a copy of self.image file. As you can seen I'm not very familiar with django and python. How can I do that better?
It may not be the most elegent way, but you could try combining save()
with a post_save
signal. Probably look something like:
class MyModel(Model):
## Stuff
def save(self, *args, **kwargs):
#create copy of img. Fixed up to use string formatting.
cp_path = "%s/copies_%s" %
(dirname(self.image.path), basename(self.image.path))
shutil.copy2(self.image.path, cp_path)
file = open(cp_path)
django_file = File(file)
django_file.name = basename(cp_path)
self.cp_image = django_file
create_watermark(self.cp_image, self.topic, self.text, 500, 45)
super(MyModel, self).save(*args, **kwargs) #to save my new ImageField
from django.dispatch import receiver
from django.db.models.signals import post_save
@receiver(post_save, sender=MyModel)
def mymodel_slug_handler(sender, instance=None, **kwargs):
if instance is not None:
new_slug = '%s-%i' % (instance.topic, instance.id)
if instance.slug != new_slug: # Stops recursion.
instance.slug = new_slug
instance.save()
精彩评论