将基于性别的默认个人资料图像放入Django

问题描述 投票:1回答:1

我需要帮助,以根据用户的性别选择默认的个人资料图片。我的媒体文件夹中有三个要用作默认值的默认图像,分别是“ 00.png,01.png和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")

我想要的是,如果用户选择性别=“ others”,则00.png应该被保存为默认值,如果他们选择了男性,那么01.png应该被选择为默认值。

请帮助🙏🙏🙏

python django if-statement django-models savechanges
1个回答
2
投票

如果您将其认为是“如果用户未上传图片,我想根据性别按其他方式默认显示[],这将变得更加容易:]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

© www.soinside.com 2019 - 2024. All rights reserved.