【发布时间】:2015-07-17 09:17:48
【问题描述】:
如果用户有个人资料图片,我想显示它。如果他/她没有个人资料图片,我想在其位置显示默认图片。
有没有办法在 Django 模型属性中加载静态图像?
注意:用户的个人资料图片使用以下代码加载。包含默认图像的else 语句不起作用。
这是我目前所拥有的:
models.py:
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
profile_picture = models.ImageField(upload_to='user/profile_pictures/',
null=False,
blank=False)
@property
def default_profile_picture(self):
if self.profile_picture:
return "%s/%s" %(settings.MEDIA_URL, self.profile_picture)
else:
return settings.STATIC_URL + 'img/default_profile_picture.jpg'
settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static", "static_dirs"),
)
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static_root")
提前感谢您的所有帮助!
【问题讨论】:
标签: django django-models django-templates django-staticfiles django-settings