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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With