Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - using instance.id while uploading image

I was referring to this youtube video, to understand how to upload image using ImageField. He has explained how to use the instance.id while saving the image. I tried it, but instance.id is returning None. Whereas for him it worked perfectly. The following is the code:

#models.py
import os

def get_image_path(instance, filename):
    return os.path.join(str(instance.id), filename)

class AdProfile(models.Model):
    name = models.CharField(max_length=100)
    profile_image = models.ImageField(upload_to=get_image_path, blank=True, null=True)

Whenever the file is saved, its saving as None/filename.

Even this link informs the same. I am using Django 10.5 and MySQL database.

What might be the problem?

like image 788
Jeril Avatar asked Dec 14 '22 22:12

Jeril


1 Answers

Django admin somehow called the get_image_path function without saving the model to database so id is None. We can override django model using save method and make sure image is saved and get_image_path get the instance with id

class AdProfile(models.Model):
    name = models.CharField(max_length=100)
    profile_image = models.ImageField(upload_to=get_image_path, blank=True, null=True)

    # Model Save override 
    def save(self, *args, **kwargs):
        if self.id is None:
            saved_image = self.profile_image
            self.profile_image = None
            super(AdProfile, self).save(*args, **kwargs)
            self.profile_image = saved_image
            if 'force_insert' in kwargs:
                kwargs.pop('force_insert')

        super(AdProfile, self).save(*args, **kwargs)
like image 155
Raja Simon Avatar answered Dec 16 '22 10:12

Raja Simon