首页 > 解决方案 > 在 django 中放置基于性别的默认个人资料图片

问题描述

我需要根据用户的性别选择默认个人资料图片的帮助。我的媒体文件夹中有三个默认图像,我想将它们用作默认值,即“00.png、01.png 和 02.png” .

模型.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")

我想要的是如果用户选择gender="others" 那么00.png 应该被保存为默认值,如果他们选择male 01.png 应该被选择为默认值..

请帮忙

标签: pythondjangoif-statementdjango-modelssavechanges

解决方案


如果您将其视为“如果用户没有上传图像,我想根据性别显示不同的默认值”,这会变得容易得多:

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

推荐阅读