python - ImageField won't delete file when using os.unlink() -


i have model:

class userprofile(models.model):     """(userprofile description)"""     user = models.foreignkey(user)     image = models.imagefield(upload_to=upload_to)      def save(self):         os.unlink(self.image.path)         super(userprofile, self).save() 

the script fails on unlink() method, , says file cannot found. ideas?

the error says

(2, 'no such file or directory')

you need more specific debugging. furthermore, way you've written code ensures errors happen. i'm not entirely sure, wouldn't surprised if value userprofile.image isn't set before userprofile record created.

so rewrite code thusly:

class userprofile(models.model):     user = models.foreignkey(user)     image = models.imagefield(upload_to=upload_to)      def save(self):         if self.image.path:             try:                 os.unlink(self.image.path)             except exception, inst:                 raise exception("unable delete %s. error: %s" % (self.image.path, inst))         super(userprofile, self).save() 

update

now think it, make sense once you're calling save, new information in self.image. if goal delete old images when saving new, going need use pre_save signal in django retrieve old record (and old image path) prior saving image. in theory, could put in save method of userprofile model, since it's intended side action not directly affect current record, i'd keep separate.

here's sample implementation:

from django.db.models import signals def delete_old_image(sender, instance, using=none):     try:         old_record = sender.objects.get(pk=instance.pk)         os.unlink(old_record.image.path)     except sender.doesnotexist:         pass signals.pre_save.connect(delete_old_image, sender=userprofile) 

you put in models.py file.


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -