From 38feb693f37be7e86fef7cb9683098eb78ec5e93 Mon Sep 17 00:00:00 2001 From: Pierre-antoine Comby Date: Fri, 6 Mar 2020 20:07:15 +0100 Subject: [PATCH] crop,resized, and save picture at the right place --- .gitignore | 2 +- apps/member/views.py | 26 +++++++++++++++++++------- apps/note/models/notes.py | 1 + 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/.gitignore b/.gitignore index b57ed74a..f9082403 100644 --- a/.gitignore +++ b/.gitignore @@ -37,7 +37,7 @@ coverage # Local data secrets.py *.log - +media/ # Virtualenv env/ venv/ diff --git a/apps/member/views.py b/apps/member/views.py index 9b185cca..870079cc 100644 --- a/apps/member/views.py +++ b/apps/member/views.py @@ -12,11 +12,12 @@ from django.urls import reverse_lazy from django.http import HttpResponseRedirect from django.db.models import Q from django.core.exceptions import ValidationError - +from django.conf import settings from django_tables2.views import SingleTableView from rest_framework.authtoken.models import Token from dal import autocomplete from PIL import Image +import io from note.models import Alias, NoteUser from note.models.transactions import Transaction @@ -230,19 +231,30 @@ class ProfilePictureUpdateView(LoginRequiredMixin, FormMixin, DetailView): return self.form_invalid(form) def form_valid(self,form): - image_file_field = form.cleaned_data['image'] + image_field = form.cleaned_data['image'] x = form.cleaned_data['x'] y = form.cleaned_data['y'] w = form.cleaned_data['width'] h = form.cleaned_data['height'] - with Image.open(image_file_field.name) as image: - image = image.crop((x, y, w+x, h+y)) - image.thumbnail((256, 256), Image.ANTIALIAS) - image.save(image_file_field.name,format=image.format) - self.object.note.display_image = image_file_field + # image crop and resize + image_file = io.BytesIO(image_field.read()) + ext = image_field.name.split('.')[-1] + image = Image.open(image_file) + image = image.crop((x, y, x+w, y+h)) + image_clean = image.resize((settings.PIC_WIDTH, + settings.PIC_RATIO*settings.PIC_WIDTH), + Image.ANTIALIAS) + image_file = io.BytesIO() + image_clean.save(image_file,ext) + image_field.file = image_file + # renaming + filename = "{}_pic.{}".format(self.object.note.pk, ext) + image_field.name = filename + self.object.note.display_image = image_field self.object.note.save() return super().form_valid(form) + class ManageAuthTokens(LoginRequiredMixin, TemplateView): """ Affiche le jeton d'authentification, et permet de le regénérer diff --git a/apps/note/models/notes.py b/apps/note/models/notes.py index 81e851d8..4b06c93a 100644 --- a/apps/note/models/notes.py +++ b/apps/note/models/notes.py @@ -45,6 +45,7 @@ class Note(PolymorphicModel): max_length=255, blank=False, null=False, + upload_to='pic/', default='pic/default.png' ) created_at = models.DateTimeField(