How to save image in django in a folder whose name is the id of the saved object?

0

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.

    
asked by Martin 13.02.2018 в 20:06
source

1 answer

1

If the primary key is auto-incremental, there is no way to know the id before calling the save method, since this is the responsibility of the database, not django. read in the documentation

An option that you could pose, is for example create the property first, and once you have your id, add the cover.

    
answered by 15.02.2018 в 11:43