For my app, I want to display a users profile picture in my navbar next to their username and also beside every post they make (very similar to facebook, twitter, etc.). I also want to let users change this profile picture by visiting a page, but I’m not exactly sure how to go about it. So far this is what I’ve done in models.py but I’m not exactly sure how my settings.py would have to change to accommodate such a feature as currently, I am unable to display even the default profile picture.
models.py
class UserProfilePicture(models.Model):
def clean_profile_picture(profile_picture):
# profile_picture = self.cleaned_data.get('profile_picture')
if profile_picture:
try:
img = Image.open(profile_picture)
width, height = img.size
if width < 60 and height < 60:
raise ValidationError("Picture uploaded must be at least 60x60 pixels.")
if width != height:
# Resize the image to fit within a 60x60 circle while maintaining aspect ratio
if width > height:
left = (width - height) / 2
right = left + height
top = 0
bottom = height
else:
top = (height - width) / 2
bottom = top + width
left = 0
right = width
img = img.crop((left, top, right, bottom))
img = img.resize((60, 60), Image.ANTIALIAS)
except IOError:
raise ValidationError('The picture uploaded is not a valid image file.')
return profile_picture
profile_picture = models.ImageField(default="profile-pictures/default-profile-pic.jpeg", upload_to='profile-pictures', validators=[clean_profile_picture])
user = models.ForeignKey('User', on_delete=models.CASCADE)
# To view the images easily in admin
def image_tag(self):
return mark_safe('<img src="/../../media/%s" width="150" height="150" />' % (self.profile_picture))