I am working on a system where there are real estate companies, which publish real estate and these have cover photos. I need to save the cover images of the properties in a route similar to this: /media/id_de_inmobiliaria/id_inmueble/portada.jpg
. The code that implements for this is the following:
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
models.py
def portada_inmueble_path(instance, file_name):
print('ID', instance.pk) //El id o pk en este punto es None
return '{}/{}/{}'.format(
instance.inmobiliaria.id,
instance.pk,
file_name)
class Inmueble(models.Model):
...
portada = models.ImageField(upload_to=portada_inmueble_path, blank=True,
null=True, max_length=99)
...
signals.py
@receiver(signals.pre_save, sender=Inmueble)
def inmueble_pre_save(sender, instance, **kwargs):
new_file = instance.portada
try:
old_file = Inmueble.objects.get(pk=instance.pk).portada
if not old_file == new_file:
if os.path.isfile(old_file.path):
os.remove(old_file.path)
except:
pass
The problem is clear, como el objeto todavia no fue guardado no tiene un id
, therefore I create a folder "None" where I keep the covers. How can I get the id of the object to create the folder and save the image in that path?
Thank you very much, if you need any other part of the code you can ask for it.