From 9bb4c87901ffaa120d28f7e8ba2836a4cda1d1aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Zahradn=C3=ADk?= Date: Sun, 10 Sep 2023 18:55:07 +0200 Subject: [PATCH] avatar-square: force square avatars, resize large ones --- trojstenid/users/forms/settings.py | 21 +++++++++++++++++++ .../users/templates/settings/profile.html | 3 +++ 2 files changed, 24 insertions(+) diff --git a/trojstenid/users/forms/settings.py b/trojstenid/users/forms/settings.py index d0d2651..f4ad21d 100644 --- a/trojstenid/users/forms/settings.py +++ b/trojstenid/users/forms/settings.py @@ -1,4 +1,10 @@ +from io import BytesIO + from django import forms +from django.core.exceptions import ValidationError +from django.core.files.images import get_image_dimensions +from PIL import Image +from PIL.Image import Resampling from trojstenid.users.models import User @@ -7,3 +13,18 @@ class ProfileForm(forms.ModelForm): class Meta: model = User fields = ["first_name", "last_name", "avatar_file"] + + def clean_avatar_file(self): + avatar = self.cleaned_data.get("avatar_file") + if avatar: + w, h = get_image_dimensions(avatar) + if w != h: + raise ValidationError("Profilová fotka musí byť štvorec.") + if w < 200: + raise ValidationError("Profilová fotka musí mať aspoň 200x200px.") + if w > 1000: + img = Image.open(avatar).convert("RGB") + img.thumbnail((1000, 1000), Resampling.BILINEAR) + avatar.file = BytesIO() + img.save(avatar.file, "jpeg") + return avatar diff --git a/trojstenid/users/templates/settings/profile.html b/trojstenid/users/templates/settings/profile.html index f29b8d0..f8c2cbf 100644 --- a/trojstenid/users/templates/settings/profile.html +++ b/trojstenid/users/templates/settings/profile.html @@ -27,6 +27,9 @@

Osobné údaje

+ {% if form.avatar_file.errors %} + {{ form.avatar_file.errors|first }} + {% endif %}