pythondjangoif-statementdjango-modelssavechanges

Place default profile image based on gender in django


I need help on selecting a default profile picture depending on the gender of the user.. I have three default images in my media folder that i want to use as defaults, namely "00.png, 01.png, and 02.png".

models.py

GenderChoice = (
    ('others', 'Others'),
    ('male', 'Male'),
    ('female' :'Female')
) 

class User(AbstractBaseUser):
    gender = models.CharField(choice=GenderChoice)
    pro_pic = models.ImageField(upload_to ="", default ="00.png")

what I want is if a user selects gender="others" then 00.png should be saved as default and if they select male the 01.png should be selected as default..

Please helpπŸ™πŸ™πŸ™


Solution

  • This becomes much easier if you think of it as "I want to show a different default based on gender if the user does not have an image uploaded":

    from django.templatetags.static import static
    class User(AbstractBaseUser):
        gender = models.CharField(choice=GenderChoice)
        pro_pic = models.ImageField(upload_to ="", null=True)
        default_pic_mapping = { 'others': '00.png', 'male': '01.png', 'female': '02.png'}
    
        def get_profile_pic_url(self):
            if not self.pro_pic:
                return static('img/{}'.format(self.default_pic_mapping[self.gender]))
            return self.pro_pic.url