我想为用户提供默认个人资料图片。我在 ImageField
上使用了默认功能,但它更像是“初始”而不是默认功能。我已经阅读了这个问题的答案:Default image for ImageField in Django's ORM ,但我想在模型级别解决问题,它不解决 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()
谁能告诉我如何为个人资料创建真实的默认图片。谢谢。
最佳答案
Ignacio 的回答很简单,但并不完美。它打破了DRY原则。您必须在所有模板中添加 {% if image %}
语句。我建议在模型上创建一个属性,它将为您处理(一次在所有地方)。
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="..."/>
关于django - 如果为空,请提供默认个人资料图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6351636/