Issue
I would like to create kind of profiles with default avatars.
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
class Someone(models.Model):
name = models.CharField(max_length=120)
gender = models.Charfield(max_length=1, choices=GENDER_CHOICES)
image = models.ImageField(upload_to='avatars', default=someone_avatar)
I'm trying to write a function which returns path to my folder with jpg.
def someone_avatar(instance):
gender = instance.gender
if gender == 'Male':
avatar = 'avatars/m.jpg'
else:
avatar = 'avatars/f.jpg'
return avatar
Obviously it doesn't work, so could you give me some advise how to solve it? Maybe I should overwrite save method? Thx.
Edited
Ok, I tried with post_save but it does't work as well:
def set_avatar(instance):
avatar = instance.image
gender = instance.gender
if gender == 'Male':
avatar = 'persons/m.jpg'
else:
avatar = 'persons/f.jpg'
return avatar
def post_save_avatar(sender, instance, *args, **kwargs):
if not instance.image:
instance.image = set_avatar(instance)
post_save.connect(post_save_avatar, sender=Person)
Maybe I shouldn't just set avatar to string like path?
Edit 2
It's working for pre_save.
Solution
Seems like you're looking for post_save signal. It gives you created
flag. So you can manually set your desired image in your handler if created
is True.
Answered By - Назар Топольський
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.