Django with django-cleanup cannot remove old files
There is a ZipPrice model describing the parts. The save method is overridden in the model, using PIL.Image, it converts the file uploaded through the form into jpeg format, creates an additional thumbnail file, and saves them under the required names. The django-cleanup module is also used to remove unnecessary files.
models.py
from PIL import Image
class ZipPrice(models.Model):
id = models.SmallAutoField(primary_key=True)
name = models.CharField(max_length=200, unique=True)
price = models.IntegerField()
full_image = models.ImageField(upload_to='zips/',
null=False, max_length=255, default=settings.DEFAULT_IMAGE['full'])
small_image = models.ImageField(upload_to='zips/',
null=False, max_length=255, default=settings.DEFAULT_IMAGE['small'])
class Meta:
db_table = 'zip_price'
ordering = ['-full_image']
def save(self, **kwargs):
with Image.open(self.full_image).convert('RGB') as img:
output_full = BytesIO()
output_small = BytesIO()
exif = img.getexif()
img.save(output_full, format='JPEG', exif=exif)
img.thumbnail((250, 250))
img.save(output_small, format='JPEG', exif=exif)
file_name = get_random_string(length=32)
self.full_image = InMemoryUploadedFile(output_full, 'full_image', f'{file_name}_full.jpg', 'image/jpeg',
sys.getsizeof(output_full), None)
self.small_image = InMemoryUploadedFile(output_small, 'small_image', f'{file_name}_small.jpg', 'image/jpeg',
sys.getsizeof(output_small), None)
super().save()
views.py
@method_decorator(login_required, name='dispatch')
class CatalogEditZip(UpdateView):
model = ZipPrice
form_class = ZipForm
success_url = reverse_lazy('catalog_zip')
template_name = 'repair/catalog_edit_zip.html'
forms.py
class ZipForm(forms.ModelForm):
class Meta:
model = ZipPrice
fields = {'name', 'price', 'full_image'}
labels = {'name': 'Name',
'price': 'Price',
'full_image': 'Image'
}
widgets = {'name': Textarea(attrs={'cols': 50, 'rows': 4})}
If i edit a model instance through a form with a new file uploaded, then everything is ok. If without loading a new file, then the following happens: the save method creates 2 new files, which is essentially redundant, however, django-cleanup cannot delete an existing file, because he is busy: PermissionError: [WinError 32] The process cannot access the file because the file is occupied by another process How can i work around this problem?