Browse Source

Refatora edição de parlamentar e verificação de imagem válida.

pull/268/head
Eduardo Calil 9 years ago
committed by Edward Ribeiro
parent
commit
490fffbf4e
  1. 2
      base/forms.py
  2. 6
      materia/models.py
  3. 9
      parlamentares/forms.py
  4. 5
      parlamentares/models.py
  5. 64
      parlamentares/views.py
  6. 1
      requirements/requirements.txt
  7. 57
      sapl/utils.py

2
base/forms.py

@ -78,7 +78,7 @@ class CasaLegislativaTabelaAuxForm(ModelForm):
row3, row3,
row4, row4,
row5, row5,
HTML("""{% if form.logotipo.value %} HTML("""{% if not form.fotografia.errors and form.fotografia.value %}
<img class="img-responsive" width="225" height="300" <img class="img-responsive" width="225" height="300"
src="{{ MEDIA_URL }}{{ form.logotipo.value }}"> src="{{ MEDIA_URL }}{{ form.logotipo.value }}">
<br /><br /> <br /><br />

6
materia/models.py

@ -4,7 +4,8 @@ from model_utils import Choices
from comissoes.models import Comissao from comissoes.models import Comissao
from parlamentares.models import Parlamentar, Partido from parlamentares.models import Parlamentar, Partido
from sapl.utils import RANGE_ANOS, YES_NO_CHOICES, xstr from sapl.utils import (restringe_tipos_de_arquivo_txt,
RANGE_ANOS, YES_NO_CHOICES, xstr)
class TipoMateriaLegislativa(models.Model): class TipoMateriaLegislativa(models.Model):
@ -457,7 +458,8 @@ class Proposicao(models.Model):
blank=True, blank=True,
null=True, null=True,
upload_to=texto_upload_path, upload_to=texto_upload_path,
verbose_name=_('Texto Original (PDF)')) verbose_name=_('Texto Original (PDF)'),
validators=[restringe_tipos_de_arquivo_txt])
class Meta: class Meta:
verbose_name = _('Proposição') verbose_name = _('Proposição')

9
parlamentares/forms.py

@ -131,15 +131,18 @@ class ParlamentaresForm (ModelForm):
row1, row2, row3, row4, row5, row1, row2, row3, row4, row5,
row6, row7, row8, row9, row10, row6, row7, row8, row9, row10,
row11, row12, row13, row11, row12, row13,
HTML("""{% if form.fotografia.value %} HTML("""
{% if not form.fotografia.errors %}
{% if form.fotografia.value %}
<img class="img-responsive" width="225" height="300" <img class="img-responsive" width="225" height="300"
src="{{ MEDIA_URL }}{{ form.fotografia.value }}"> src="{{ MEDIA_URL }}{{ form.fotografia.value }}">
<br /><br /> <br /><br />
<input type="submit" <input type="submit"
name="remover" name="remover-foto"
id="remover" id="remover-foto"
class="btn btn-warning" class="btn btn-warning"
value="Remover Foto"/> value="Remover Foto"/>
{% endif %}
{% endif %}""", ), {% endif %}""", ),
row14, row14,
form_actions()) form_actions())

5
parlamentares/models.py

@ -4,7 +4,7 @@ from django.db import models
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from model_utils import Choices from model_utils import Choices
from sapl.utils import UF, YES_NO_CHOICES from sapl.utils import restringe_tipos_de_arquivo_img, UF, YES_NO_CHOICES
class Legislatura(models.Model): class Legislatura(models.Model):
@ -241,7 +241,8 @@ class Parlamentar(models.Model):
blank=True, blank=True,
null=True, null=True,
upload_to=foto_upload_path, upload_to=foto_upload_path,
verbose_name=_('Fotografia')) verbose_name=_('Fotografia'),
validators=[restringe_tipos_de_arquivo_img])
class Meta: class Meta:
verbose_name = _('Parlamentar') verbose_name = _('Parlamentar')

64
parlamentares/views.py

@ -1,9 +1,11 @@
import os import os
from braces.views import FormMessagesMixin
from django.contrib import messages from django.contrib import messages
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse, reverse_lazy
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.views.generic import FormView from django.views.generic import CreateView, FormView, UpdateView
from crud import Crud from crud import Crud
@ -139,45 +141,27 @@ class ParlamentaresCadastroView(FormView):
{'form': form, 'legislatura_id': pk}) {'form': form, 'legislatura_id': pk})
class ParlamentaresEditarView(FormView): class ParlamentaresEditarView(UpdateView):
template_name = "parlamentares/parlamentares_cadastro.html" template_name = "parlamentares/parlamentares_cadastro.html"
form_class = ParlamentaresEditForm
def get_success_url(self): model = Parlamentar
return reverse('parlamentares') success_url = reverse_lazy('parlamentares')
def get(self, request, *args, **kwargs): def form_valid(self, form):
pk = kwargs['pk'] parlamentar = form.instance
parlamentar = Parlamentar.objects.get(pk=pk) if 'salvar' in self.request.POST:
form = ParlamentaresEditForm(instance=parlamentar) form.save()
return self.render_to_response( elif 'excluir' in self.request.POST:
{'form': form, 'object': parlamentar}) Mandato.objects.get(parlamentar=parlamentar).delete()
parlamentar.delete()
def post(self, request, *args, **kwargs): elif "remover-foto" in self.request.POST:
pk = kwargs['pk'] try:
parlamentar = Parlamentar.objects.get(pk=pk) os.unlink(parlamentar.fotografia.path)
form = ParlamentaresEditForm(request.POST, instance=parlamentar) except OSError:
pass # Should log this error!!!!!
if form.is_valid(): parlamentar.fotografia = None
if 'salvar' in request.POST: parlamentar.save()
parlamentar = form.save(commit=False) return HttpResponseRedirect(self.get_success_url())
if 'fotografia' in request.FILES:
parlamentar.fotografia = request.FILES['fotografia']
parlamentar.biografia = form.data['biografia']
parlamentar.save()
elif 'excluir' in request.POST:
Mandato.objects.get(parlamentar=parlamentar).delete()
parlamentar.delete()
elif "remover" in request.POST:
try:
os.unlink(parlamentar.fotografia.path)
except OSError:
pass # Should log this error!!!!!
parlamentar = form.save(commit=False)
parlamentar.fotografia = None
parlamentar.save()
return self.form_valid(form)
else:
return self.render_to_response({'form': form})
class ParlamentaresDependentesView(FormView): class ParlamentaresDependentesView(FormView):

1
requirements/requirements.txt

@ -17,3 +17,4 @@ pytz==2015.7
pyyaml==3.11 pyyaml==3.11
rtyaml==0.0.2 rtyaml==0.0.2
unipath==1.1 unipath==1.1
python-magic==0.4.10

57
sapl/utils.py

@ -1,10 +1,13 @@
from datetime import date from datetime import date
from functools import wraps from functools import wraps
from django.apps import apps from django.apps import apps
from django.contrib import admin from django.contrib import admin
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
import magic
autor_label = ''' autor_label = '''
<div class="col-xs-12"> <div class="col-xs-12">
@ -119,3 +122,57 @@ UF = [
] ]
RANGE_ANOS = [(year, year) for year in range(date.today().year, 1889, -1)] RANGE_ANOS = [(year, year) for year in range(date.today().year, 1889, -1)]
TIPOS_TEXTO_PERMITIDOS = (
'application/vnd.oasis.opendocument.text',
'application/x-vnd.oasis.opendocument.text',
'application/pdf',
'application/x-pdf',
'application/acrobat',
'applications/vnd.pdf',
'text/pdf',
'text/x-pdf',
'text/plain',
'application/txt',
'browser/internal',
'text/anytext',
'widetext/plain',
'widetext/paragraph',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
)
TIPOS_IMG_PERMITIDOS = (
'image/jpeg',
'image/jpg',
'image/jpe_',
'image/pjpeg',
'image/vnd.swiftview-jpeg',
'application/jpg',
'application/x-jpg',
'image/pjpeg',
'image/pipeg',
'image/vnd.swiftview-jpeg',
'image/x-xbitmap',
'image/bmp',
'image/x-bmp',
'image/x-bitmap',
'image/png',
'application/png',
'application/x-png',
)
def fabrica_validador_de_tipos_de_arquivo(lista):
def restringe_tipos_de_arquivo(value):
mime = magic.from_buffer(value.read(), mime=True)
mime = mime.decode()
if mime not in lista:
raise ValidationError(_('Tipo de arquivo não suportado'))
return restringe_tipos_de_arquivo
restringe_tipos_de_arquivo_txt = fabrica_validador_de_tipos_de_arquivo(
TIPOS_TEXTO_PERMITIDOS)
restringe_tipos_de_arquivo_img = fabrica_validador_de_tipos_de_arquivo(
TIPOS_IMG_PERMITIDOS)

Loading…
Cancel
Save