问题描述
|
我想为用户提供默认的个人资料图片。我已经在ѭ0上使用了默认功能,但是它的行为比默认值更像\'initial \'。我已经阅读了以下问题的答案:Django的ORM中ImageField的默认图像,但我想在模型级别解决该问题,并且无法解决FK关系。
这是我目前拥有的:
class Avatar(models.Model):
avatar = models.ImageField(upload_to=upload_to)
avatar_thumbnail = models.ImageField(upload_to=upload_to)
profile = models.ForeignKey(UserProfile)
class UserProfile(models.Model):
user = models.ForeignKey(User,unique=True)
...
我已经尝试将以下函数添加到UserProfile模型中(而且很可能是不正确的代码)-
# in UserProfile(models.Model)
def create_default_avatar(self):
if not self.avatar_set.all():
avatar = profile.avatar_set.create(profile=self.__class__)
avatar.avatar = File(open(\'media/default_profile_picture.jpg\'))
avatar.avatar_thumbnail = File(open(\'media/default_profile_picture_thumbnail.jpg\'))
avatar.save()
有人可以告诉我如何为个人资料创建真实的默认图片。谢谢。
解决方法
如果要使用默认值,则不在字段中存储任何内容,并使用
{% if %}
模板标签进行检测。
, 伊格纳西奥的答案很简单,但并不完美。它违反了DRY原理。您必须在所有模板中添加“ 4”语句。我建议在模型上创建一个属性,该属性将为您处理(一次在所有地方)。
class Avatar(models.Model):
(...)
@property
def avatar_image_url(self):
# Pseudocode:
if has image:
return url to the image
else:
return url to default image
然后,您可以在模板中执行以下操作:
<img src=\"{{ item.avatar_image_url }}\" alt=\"...\"/>