Provide a default profile picture if ever empty
I would like to provide a default profile picture for a user. I've used the default feature on the ImageField
, but it acts more like an 'initial' than a default. I've read over the answers to this question: Default image for ImageField in Django's ORM, but I'd like to solve the problem at the model level and it does not address with FK relationships.
Here is what I currently have:
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)
...
I've tried adding the following function to the UserProfile model (and more than likely, incorrect code) --
# 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()
Could someone please show me how to create a true default picture for a profile. Thank you.
Ignacio's answer is simple but not perfect. It breaks the DRY principle. You have to add in all your templates the {% if image %}
statements. I suggest creating a property on on the model, which will handle that for you (in all places at once).
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
Then in template you just do:
<img src="{{ item.avatar_image_url }}" alt="..."/>
Store nothing in the field if the default is to be used, and use the {% if %}
template tag to detect this.
精彩评论