Issue
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?
Solution
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)
Answered By - Raja Simon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.