Answer the question
In order to leave comments, you need to log in
Why are downloaded files not deleted?
Hello!
Started learning django, decided to make a photo gallery as a workout.
I upload photos through the admin panel, everything turns out with a bang: both the photos themselves and the thumbnails. But it is not possible to delete from the admin panel: the entry is deleted, but the files themselves remain. At first I decided that the problem was in access rights, I did chmod 777 photos - it did not help.
Help! I don't know what's wrong!
Here is the contents of models:
from django.db import models
from items.fields.ThumbnailImageField import ThumbnailImageField
class Album(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
def __unicode__(self):
return self.name
class Photo(models.Model):
item = models.ForeignKey(Album)
title = models.CharField(max_length=100)
image = ThumbnailImageField(upload_to='photos')
caption = models.CharField(max_length=250, blank=True)
def __unicode__(self):
return self.title
from django.db.models.fields.files import ImageField, ImageFieldFile
from PIL import Image
import os
def _add_thumb(s):
parts = s.split(".")
parts.insert(-1, "thumb")
if parts[-1].lower() not in ['jpeg', 'jpg']:
parts[-1] = 'jpg'
return ".".join(parts)
class ThumbnailImageFieldFile(ImageFieldFile):
def _get_thumb_path(self):
return _add_thumb(self.path)
thumb_path = property(_get_thumb_path)
def _get_thumb_url(self):
return _add_thumb(self.url)
thumb_url = property(_get_thumb_url)
def save(self, name, content, save=True):
super(ThumbnailImageFieldFile, self).save(name, content, save)
img = Image.open(self.path)
img.thumbnail(
(self.field.thumb_width, self.field.thumb_height),
Image.ANTIALIAS
)
img.save(self.thumb_path, 'JPEG')
def delete(self, save=True):
if os.path.exists(self.thumb_path):
os.remove(self.thumb_path)
super(ThumbnailImageFieldFile, self).delete(save)
class ThumbnailImageField(ImageField):
attr_class = ThumbnailImageFieldFile
def __init__(self, thumb_width=128, thumb_height=128, *args, **kwargs):
self.thumb_width = thumb_width
self.thumb_height = thumb_height
super(ThumbnailImageField, self).__init__(*args, **kwargs)
Answer the question
In order to leave comments, you need to log in
When deleting models, delete for FileField is not called. Prior to django 1.3, they somehow tried to delete files, but there were certain problems. Since 1.3 they've stopped deleting files altogether. As I understand it, they have a problem with transactions.
As advised above, django-cleanup will help you to delete files, and for resizing, for example, sorl-thumbnail, easy-thumbnail or django-resized.
Such is Django's policy. "Whatever is 'created' in Vegas stays in Vegas"
Django does not delete uploaded files. =) Use
un1t 's django-cleanup app .pip install django-cleanup
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question