What I’m trying to accomplish is when the object is created I want to make a new directory static/images/slug/(images go here). Additionally, I want the directory to be deleted when the object is deleted (I currently delete the images with signals). I’ve read online a few different ways to do it but I haven’t successfully been able to accomplish it. What is the best practice for this to be completed?
class Property(models.Model):
property_num = models.IntegerField()
property_road = models.CharField(max_length=200)
rent = models.IntegerField(default=1000)
city = models.CharField(max_length=200)
state = models.CharField(choices=STATE_CHOICE, max_length=25)
zip = models.IntegerField()
bedrooms = models.IntegerField()
bathrooms = models.FloatField(max_length=3)
sq_foot = models.IntegerField()
property_title = models.CharField(max_length=200, blank=True, null=True)
property_short_description = CKEditor5Field('text', config_name='extends', blank = True, null = True)
description = CKEditor5Field('text', config_name='extends')
is_active = models.BooleanField(default=True)
thumbnail = models.ImageField(upload_to='static/images', blank=True)
slug = models.SlugField(blank=True, null=True, unique=True, allow_unicode=True)
available_date = models.DateField(max_length=200, blank=True, null=True)
def __str__(self):
return '{} {}'.format(self.property_num, self.property_road)
@property
def address(self):
return '{} {}'.format(self.property_num, self.property_road)
def save(self, *args, **kwargs):
if self.slug is None:
slug = slugify(self.address)
has_slug = Property.objects.filter(slug=slug)
count = 1
while has_slug:
count += 1
slug = slugify(self.address) + '-' + str(count)
has_slug = Property.objects.filter(slug=slug)
self.slug = slug
super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse('base:properties')
def file_upload_location(self):
return 'static/images/{}'.format(self.slug)
class PropertyImage(models.Model):
property = models.ForeignKey(Property, related_name='images', on_delete=models.CASCADE)
image = models.ImageField(upload_to='static/images')