我想爲用戶提供默認配置文件圖片。我使用了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)
...
我試着添加以下功能到用戶配置模型(以及更可能的,不正確的代碼) -
# 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()
可能有人請告訴我如何爲個人資料創建真實的默認圖片。謝謝。