From 7cb84b572b5658e9d45e0f4803e7a10db868cce7 Mon Sep 17 00:00:00 2001 From: Eduardo Calil Date: Mon, 22 Feb 2016 13:56:52 -0300 Subject: [PATCH] =?UTF-8?q?Valida=20se=20imagem=20=C3=A9=20.jpeg,=20.bpm?= =?UTF-8?q?=20ou=20.png=20em=20edicao=20de=20parlamentar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- parlamentares/views.py | 49 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/parlamentares/views.py b/parlamentares/views.py index e39b54447..6c9fc5822 100644 --- a/parlamentares/views.py +++ b/parlamentares/views.py @@ -7,6 +7,9 @@ from django.utils.html import strip_tags from django.utils.translation import ugettext_lazy as _ from django.views.generic.edit import FormMixin from vanilla import GenericView +from django.forms.fields import ImageField +from io import BytesIO +from django.core.exceptions import ValidationError from crud import build_crud @@ -256,6 +259,40 @@ class ParlamentaresCadastroView(FormMixin, GenericView): {'form': form, 'legislatura_id': pk}) +class DmitryImageField(ImageField): + + def to_python(self, data): + f = super(DmitryImageField, self).to_python(data) + if f is None: + return None + + try: + from PIL import Image + except ImportError: + import Image + + if hasattr(data, 'temporary_file_path'): + file = data.temporary_file_path() + else: + if hasattr(data, 'read'): + file = BytesIO(data.read()) + else: + file = BytesIO(data['content']) + + try: + im = Image.open(file) + if im.format not in ('BMP', 'PNG', 'JPEG'): + return -1 + except ImportError: + return -2 + except Exception: + return -3 + + if hasattr(f, 'seek') and callable(f.seek): + f.seek(0) + return f + + class ParlamentaresEditarView(FormMixin, GenericView): template_name = "parlamentares/parlamentares_cadastro.html" @@ -279,6 +316,17 @@ class ParlamentaresEditarView(FormMixin, GenericView): parlamentar = form.save(commit=False) if 'fotografia' in request.FILES: parlamentar.fotografia = request.FILES['fotografia'] + valida_imagem = DmitryImageField() + # import ipdb; ipdb.set_trace() + try: + valida_imagem.to_python(request.FILES['fotografia']) + except ValidationError: + mensagem = "Por favor, insira uma imagem vĂ¡lida dos formatos\ + JPEG, PNG ou BMP" + messages.add_message(request, messages.INFO, mensagem) + return self.render_to_response({'form': form}) + else: + pass parlamentar.biografia = sub(' ', ' ', strip_tags(form.data['biografia'])) @@ -294,7 +342,6 @@ class ParlamentaresEditarView(FormMixin, GenericView): parlamentar = form.save(commit=False) parlamentar.fotografia = None parlamentar.save() - return self.form_valid(form) else: return self.render_to_response({'form': form})