Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need more specific debugging. Furthermore, the way you've written the code probably ensures errors will happen. I'm not entirely sure, but I wouldn't be surprised if the value for UserProfile.image isn't set before a UserProfile record is created.</p> <p>So I would rewrite your code thusly:</p> <pre><code>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 to delete %s. Error: %s" % (self.image.path, inst)) super(UserProfile, self).save() </code></pre> <h1>Update</h1> <p>Now that I think about it, it does make sense that once you're calling save, the new information is already in self.image. If your goal is to delete the old images when saving the new, you are going to need to use the <a href="http://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.pre_save" rel="nofollow">pre_save signal in Django</a> to retrieve the old record (and thus the old image path) <em>prior</em> to saving the image. In theory, you <em>could</em> put this in the <code>save</code> method of the <code>UserProfile</code> model, but since it's intended as a side action that does not directly affect the <strong>current</strong> record, I'd keep it separate.</p> <p>Here's a sample implementation:</p> <pre><code>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) </code></pre> <p>You would put this in your <code>models.py</code> file.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload