python - 在 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 应该被选择为默认值..
请帮忙
解决方案
如果您将其视为“如果用户没有上传图像,我想根据性别显示不同的默认值”,这会变得容易得多:
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
推荐阅读
- cython - 从 Cython 中的自定义 C++ 库中键入?
- ios - 呈现 EKEventViewController
- named-ranges - 当使用 OFFSET 构建范围时,使用命名范围的 TransferSpreadsheet 不起作用
- python - 如何阻止程序覆盖现有的文本文件
- javascript - 我在 heroku 上部署了我的应用程序,但在运行 heroku logs tail “连接到数据库时出错”时出现此错误
- laravel - Laravel Eloquent hasMany 具体关系行返回
- flutter - 摆脱 PageView Flutter 上的灰色矩形覆盖
- c# - 我应该像这样将服务工厂注入我的 Blazor 页面吗?
- css - 为什么从 flex: column 转到 flex: row 时内容不显示?
- authentication - 我使用哪些凭据和工具对 HERE 地理围栏/车队 API 进行身份验证?