Login

FieldField Auto delete file on change or delete

Author:
hieunv495
Posted:
January 17, 2018
Language:
Python
Version:
1.8
Tags:
field File
Score:
0 (after 0 ratings)

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

Comments

Please login first before commenting.