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)