Issue
i have edited the user profile photo with PIL library and trying to display the new image in my django template but somehow the image is not displaying ,here is my code in views.py :
enterim = Image.open(get_user_model().objects.get(username=request.user).avatar)
width, height = im.size
newsize = (50, 50)
image = im.resize(newsize)
buffer = BytesIO()
image.save(buffer, "PNG")
img_str = buffer.getvalue()
return render(request, '../templates/templates_v2/update_location.html', {'updatelocation_form': updatelocation_form,'user_info':user_info,'img_str':img_str})
and this is the img tag in html template:
<img src='data:image/png;"+ {{img_str}} + "'/>
Thanks in advance
Solution
What you are trying to do is modify the size of the user's avatar, I do this process from the models using signals. example:
from PIL import Image
from django.dispatch import receiver
from django.db.models.signals import post_save
class User(AbstractUser):
avatar = models.ImageField(default='avatar.png', upload_to='users/')
what this simple user model consists of, and from that I carry out the process of modifying the image with signals.
@receiver(post_save, sender=User)
def set_avatar_user(sender, instance, *args, **kwargs):
if instance.avatar:
img = Image.open(instance.avatar.path)
if img.width > 400 and img.height > 400:
size = (400, 400)
img.thumbnail(size)
img.save(instance.avatar.path)
and when you save the model, the image is modified to the size you assigned it, and to call the image from a template it would be {{ request.user.avatar.url }}
Answered By - cosmos multi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.