简体   繁体   中英

Django instance return none from ImageField

How could I solve this problem? I want to create a model with an image and upload it to create a folder with the id of that object.

When I try to upload an image in the same class I can't reference the id to add in the url. The path looks like: http://127.0.0.1:8000/media/foto_pacientes/None/image.png

pacientes.models.py

    class Pacientes(models.Model):
        id = models.AutoField(primary_key=True)
        foto = models.ImageField(blank=True, null=True, upload_to=foto_paciente)

    def foto_paciente(instance,filename):
        print(instance)
        return '/'.join(['foto_pacientes', str(instance.id.id), filename])

However, when I try to upload an image using a ForeginKey I can get the desired id. As: http://127.0.0.1:8000/media/foto_pacientes/1/image.png

imagens.model.py

def imagens_historico(instance, filename):
    print(instance)
    return '/'.join(['historico', str(instance.id_historico.id_historico), filename])


class ImagensHistorico(models.Model):
    id_imagem_historico = models.AutoField(primary_key=True)
    imagem = models.ImageField(blank=True, null=True, upload_to=imagens_historico)
    id_historico = models.ForeignKey(Historicos, related_name='imagens',
                                     on_delete=models.CASCADE, blank=False, null=False)

Well you cannot reference the id of the object which has not been created yet. What you can do is use the primary key of the object to create the folder to store the image .

Remove the field id_imagem_historico = models.AutoField(primary_key=True) If required , keep it .

This problem can easily be solved via this method . Put it in your models.py

The code :

def get_new_image_file_path(self , filename):
    return "imagens_historico/{}/image_name.png".format(self.pk)

class ImagensHistorico(models.Model):
    imagem = models.ImageField(blank=True, null=True, upload_to=get_new_image_file_path)
    id_historico = models.ForeignKey(Historicos, related_name='imagens',
                                     on_delete=models.CASCADE, blank=False, null=False)

This will solve your problem and what you want is easily acheived.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM