FileField delete file on delete or update
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | from django.db import models
from django.utils.text import slugify
from django.dispatch import receiver
import os
# Create your models here.
def get_unique_slug(model,field_name,value):
max_length = model._meta.get_field(field_name).max_length
slug = slugify(value)
num = 1
unique_slug = '{}-{}'.format(slug[:max_length - len(str(num)) - 1], num)
while model.objects.filter(** {field_name: unique_slug}).exists():
unique_slug = '{}-{}'.format(slug[:max_length - len(str(num)) - 1], num)
num += 1
return unique_slug
class Post(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
slug = models.SlugField(max_length=5, unique=True, blank=True, editable=False)
slug2 = models.SlugField(max_length=10, blank=True, editable=False)
def __str__(self):
return self.slug
def save(self, *args, **kwargs):
if not self.slug:
self.slug = get_unique_slug(self.__class__,'slug',self.name)
if not self.slug2:
self.slug2 = get_unique_slug(self.__class__,'slug2',self.name)
super().save(*args, **kwargs)
class Image(models.Model):
post = models.ForeignKey(Post, related_name='images')
file = models.ImageField(upload_to='upload')
position = models.PositiveSmallIntegerField(default=0)
class Meta:
ordering = ['position']
def __str__(self):
return '%s - %s ' % (self.post, self.file)
@receiver(models.signals.post_delete, sender=Image)
def auto_delete_file_on_delete(sender, instance, **kwargs):
"""
Deletes file from filesystem
when corresponding `MediaFile` object is deleted.
"""
if instance.file:
if os.path.isfile(instance.file.path):
os.remove(instance.file.path)
@receiver(models.signals.pre_save, sender=Image)
def auto_delete_file_on_change(sender, instance, **kwargs):
"""
Deletes old file from filesystem
when corresponding `MediaFile` object is updated
with new file.
"""
if not instance.pk:
return False
try:
old_file = sender.objects.get(pk=instance.pk).file
except sender.DoesNotExist:
return False
new_file = instance.file
if not old_file == new_file:
if os.path.isfile(old_file.path):
os.remove(old_file.path)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Thank you for this <3
#
Thank you very very much!
#
Please login first before commenting.