I’m using django and jquery for image uploading. First we upload an image using the uploader, the image get stored in the tmpbg imagefield. Then if we click save button, the tmpbg will be moved to the background imagefield. Here what I need is I want to delete the orphaned image file in the background imagefield path.
Here is the code
Models.py:
class BackgroundModel(models.Model):
user = models.OneToOneField(User)
background = models.ImageField(upload_to='backgrounds', null=True, blank=True)
tmpbg = models.ImageField(upload_to='backgrounds', null=True, blank=True)
class BackgroundModelForm(ModelForm):
class Meta:
model = BackgroundModel
exclude = ('user', 'background')
Views.py (The code for deleting the image file in the path):
try:
bg = BackgroundModel.objects.get(user=request.user)
except BackgroundModel.DoesNotExist:
pass
else:
if bg.background != '':
image_path = os.path.join(settings.MEDIA_ROOT, str(bg.background))
try:
os.unlink(image_path)
bg.BackgroundModel.delete()
except:
pass
bg.background = bg.tmpbg
return HttpResponse("")
But the orphaned imagefile is not deleted. What mistakes have I done?
UPDATE:
There is a problem in this line
bg.background=bg.tmpbg
When I checked in the shell mode. It shows none.
>>> g.background
<ImageFieldFile: None>
But there is an image file in tmpbg
>>> g.background
<ImageFieldFile: backgrounds/ijkl.jpg>
So, How can I copy from one imagefield to another field?
Between the image_path code is Correct!.
Try with
os.normpath, this should do the trick :UPDATE :