From 6ac03730933d2ce5c27e25abe612b7dd9ef27dd2 Mon Sep 17 00:00:00 2001 From: LeandroRoberto Date: Thu, 29 Sep 2016 17:35:27 -0300 Subject: [PATCH] =?UTF-8?q?Aplica=20refatora=C3=A7=C3=A3o=20do=20crud=20na?= =?UTF-8?q?=20App=20Base?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sapl/base/models.py | 6 +- sapl/base/templatetags/common_tags.py | 1 + sapl/base/urls.py | 1 - sapl/base/views.py | 66 ++++++++++----------- sapl/comissoes/models.py | 1 - sapl/comissoes/views.py | 12 ++-- sapl/crispy_layout_mixin.py | 2 +- sapl/crud/base.py | 20 +++---- sapl/crud/masterdetail.py | 82 --------------------------- sapl/crud/urls.py | 9 --- sapl/materia/models.py | 4 +- sapl/materia/tests/test_materia.py | 2 +- sapl/materia/views.py | 2 +- sapl/norma/views.py | 1 - sapl/protocoloadm/views.py | 10 ++-- sapl/sessao/views.py | 3 +- sapl/utils.py | 4 +- 17 files changed, 56 insertions(+), 170 deletions(-) delete mode 100644 sapl/crud/masterdetail.py diff --git a/sapl/base/models.py b/sapl/base/models.py index 12e840fda..5b4502e09 100644 --- a/sapl/base/models.py +++ b/sapl/base/models.py @@ -1,21 +1,17 @@ from builtins import LookupError from django.apps import apps -from django.conf.urls import include, url from django.contrib.auth.management import _get_all_permissions from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.core import exceptions -from django.db import models from django.db import models, router from django.db.utils import DEFAULT_DB_ALIAS -from django.utils.translation import string_concat from django.utils.translation import ugettext_lazy as _ -from rest_framework import permissions +from django.utils.translation import string_concat from sapl.utils import UF, YES_NO_CHOICES - TIPO_DOCUMENTO_ADMINISTRATIVO = (('O', _('Ostensivo')), ('R', _('Restritivo'))) diff --git a/sapl/base/templatetags/common_tags.py b/sapl/base/templatetags/common_tags.py index ec21ce48b..c926a485d 100644 --- a/sapl/base/templatetags/common_tags.py +++ b/sapl/base/templatetags/common_tags.py @@ -127,6 +127,7 @@ def get_config_not_exists(user): else: return False + @register.filter def str2intabs(value): if not isinstance(value, str): diff --git a/sapl/base/urls.py b/sapl/base/urls.py index 22691759d..1cfb5a395 100644 --- a/sapl/base/urls.py +++ b/sapl/base/urls.py @@ -12,7 +12,6 @@ from .views import (AppConfigCrud, CasaLegislativaCrud, HelpView, RelatorioMateriasTramitacaoView, RelatorioPresencaSessaoView) - app_name = AppConfig.name diff --git a/sapl/base/views.py b/sapl/base/views.py index 2e48efc3a..c7f869400 100644 --- a/sapl/base/views.py +++ b/sapl/base/views.py @@ -5,15 +5,12 @@ from django.db.models import Count, Q from django.http import HttpResponseRedirect from django.utils.translation import ugettext_lazy as _ from django.views.generic.base import TemplateView -from django.views.generic.edit import BaseCreateView from django_filters.views import FilterView -from sapl.crud.base import (Crud, CrudBaseMixin, CrudCreateView, - CrudDetailView, CrudUpdateView) +from sapl.crud.base import CrudAux from sapl.materia.models import MateriaLegislativa, TipoMateriaLegislativa from sapl.parlamentares.models import Parlamentar from sapl.sessao.models import OrdemDia, SessaoPlenaria -from sapl.utils import permissao_tb_aux from .forms import (CasaLegislativaForm, ConfiguracoesAppForm, RelatorioAtasFilterSet, @@ -226,24 +223,15 @@ class RelatorioMateriasPorAutorView(FilterView): return context -class CasaLegislativaCrud(Crud): +class CasaLegislativaCrud(CrudAux): model = CasaLegislativa help_path = '' - class BaseMixin(CrudBaseMixin): + class BaseMixin(CrudAux.BaseMixin): list_field_names = ['codigo', 'nome', 'sigla'] - - def has_permission(self): - return permissao_tb_aux(self) - - class CreateView(CrudCreateView): form_class = CasaLegislativaForm - class UpdateView(CrudUpdateView): - form_class = CasaLegislativaForm - - class DetailView(CrudDetailView): - form_class = CasaLegislativaForm + class DetailView(CrudAux.DetailView): def get(self, request, *args, **kwargs): return HttpResponseRedirect( @@ -258,28 +246,22 @@ class HelpView(PermissionRequiredMixin, TemplateView): return ['ajuda/%s.html' % self.kwargs['topic']] -class SistemaView(PermissionRequiredMixin, TemplateView): - template_name = 'sistema.html' - permission_required = '' - - def has_permission(self): - return permissao_tb_aux(self) - - -class AppConfigCrud(Crud): +class AppConfigCrud(CrudAux): model = AppConfig help_path = '' - class BaseMixin(CrudBaseMixin): - list_field_names = ['documentos_administrativos', - 'sequencia_numeracao', - 'painel_aberto'] + class BaseMixin(CrudAux.BaseMixin): + form_class = ConfiguracoesAppForm - def has_permission(self): - return permissao_tb_aux(self) + @property + def list_url(self): + return '' - class CreateView(CrudCreateView): - form_class = ConfiguracoesAppForm + @property + def create_url(self): + return '' + + class CreateView(CrudAux.CreateView): def get(self, request, *args, **kwargs): app_config = AppConfig.objects.last() @@ -289,8 +271,20 @@ class AppConfigCrud(Crud): kwargs={'pk': app_config.pk})) else: self.object = None - return super(BaseCreateView, self).get( + return super(CrudAux.CreateView, self).get( request, *args, **kwargs) - class UpdateView(CrudUpdateView): - form_class = ConfiguracoesAppForm + class ListView(CrudAux.ListView): + + def get(self, request, *args, **kwargs): + return HttpResponseRedirect(reverse('sapl.base:appconfig_create')) + + class DetailView(CrudAux.DetailView): + + def get(self, request, *args, **kwargs): + return HttpResponseRedirect(reverse('sapl.base:appconfig_create')) + + class DeleteView(CrudAux.DeleteView): + + def get(self, request, *args, **kwargs): + return HttpResponseRedirect(reverse('sapl.base:appconfig_create')) diff --git a/sapl/comissoes/models.py b/sapl/comissoes/models.py index 60aee6368..ee3f72e6f 100644 --- a/sapl/comissoes/models.py +++ b/sapl/comissoes/models.py @@ -1,4 +1,3 @@ -import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ diff --git a/sapl/comissoes/views.py b/sapl/comissoes/views.py index 8207ac290..a3817c3e5 100644 --- a/sapl/comissoes/views.py +++ b/sapl/comissoes/views.py @@ -1,13 +1,9 @@ -from django.contrib.auth.decorators import permission_required -from django.contrib.auth.mixins import PermissionRequiredMixin + from django.core.urlresolvers import reverse from django.views.generic import ListView -from sapl.crud.base import (Crud, CrudBaseMixin, CrudCreateView, - CrudDeleteView, CrudListView, CrudUpdateView, - MasterDetailCrud, CrudAux) -from sapl.materia.models import MateriaLegislativa, Tramitacao -from sapl.utils import permissao_tb_aux, permissoes_comissoes +from sapl.crud.base import Crud, CrudAux, MasterDetailCrud +from sapl.materia.models import MateriaLegislativa from .models import (CargoComissao, Comissao, Composicao, Participacao, Periodo, TipoComissao) @@ -77,7 +73,7 @@ class MateriasTramitacaoListView(ListView): materias = MateriaLegislativa.objects.filter(tramitacao__isnull=False) for materia in materias: comissao = materia.tramitacao_set.last( - ).unidade_tramitacao_local.comissao + ).unidade_tramitacao_local.comissao if comissao: if comissao.pk == int(self.kwargs['pk']): lista.append(materia) diff --git a/sapl/crispy_layout_mixin.py b/sapl/crispy_layout_mixin.py index 89dd2da8e..738c48110 100644 --- a/sapl/crispy_layout_mixin.py +++ b/sapl/crispy_layout_mixin.py @@ -1,12 +1,12 @@ from math import ceil +import rtyaml from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import HTML, Div, Fieldset, Layout, Submit from django import template from django.utils import formats from django.utils.translation import ugettext as _ -import rtyaml def heads_and_tails(list_of_lists): diff --git a/sapl/crud/base.py b/sapl/crud/base.py index d480684b6..1816b8b3e 100644 --- a/sapl/crud/base.py +++ b/sapl/crud/base.py @@ -4,21 +4,17 @@ from braces.views import FormMessagesMixin from compressor.utils.decorators import cached_property from crispy_forms.bootstrap import FieldWithButtons, StrictButton from crispy_forms.helper import FormHelper -from crispy_forms.layout import Layout, Field +from crispy_forms.layout import Field, Layout from django import forms -from django.apps import apps from django.conf.urls import url -from django.contrib.auth.management import _get_all_permissions from django.contrib.auth.mixins import PermissionRequiredMixin -from django.core import exceptions from django.core.urlresolvers import reverse -from django.db import models, router -from django.db.utils import DEFAULT_DB_ALIAS +from django.db import models from django.http.response import Http404 -from django.shortcuts import redirect from django.utils.decorators import classonlymethod from django.utils.encoding import force_text -from django.utils.translation import ugettext_lazy as _, string_concat +from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import string_concat from django.views.generic import (CreateView, DeleteView, DetailView, ListView, UpdateView) from django.views.generic.base import ContextMixin @@ -27,7 +23,6 @@ from django.views.generic.list import MultipleObjectMixin from sapl.crispy_layout_mixin import CrispyLayoutFormMixin, get_field_display from sapl.utils import normalize - logger = logging.getLogger(__name__) ACTION_LIST, ACTION_CREATE, ACTION_DETAIL, ACTION_UPDATE, ACTION_DELETE = \ @@ -1056,7 +1051,8 @@ class MasterDetailCrud(Crud): @property def detail_list_url(self): obj = self.crud if hasattr(self, 'crud') else self - if not obj.ListView.permission_required or self.request.user.has_perm(self.permission(RP_LIST)): + if not obj.ListView.permission_required or\ + self.request.user.has_perm(self.permission(RP_LIST)): if '__' in obj.parent_field: fields = obj.parent_field.split('__') parent_object = self.object @@ -1121,13 +1117,13 @@ class MasterDetailCrud(Crud): @property def detail_root_detail_url(self): """ - Implementar retorno para o parent_field imediato no caso de + Implementar retorno para o parent_field imediato no caso de edição em cascata de MasterDetailDetail... """ return '' obj = self.crud if hasattr(self, 'crud') else self if hasattr(obj, 'parent_field'): - parent_field = obj.parent_field.split('__')[0] + # parent_field = obj.parent_field.split('__')[0] root_pk = self.object .pk pk = root_pk diff --git a/sapl/crud/masterdetail.py b/sapl/crud/masterdetail.py deleted file mode 100644 index 91c8de5ba..000000000 --- a/sapl/crud/masterdetail.py +++ /dev/null @@ -1,82 +0,0 @@ -from django.utils.decorators import classonlymethod - -from .base import (ACTION_CREATE, ACTION_LIST, Crud, CrudBaseMixin, CrudCreateView, - CrudDeleteView, CrudDetailView, CrudListView, - CrudUpdateView) - - -class MasterDetailCrud__OBSOLETO(Crud): - - class BaseMixin(CrudBaseMixin): - - @property - def list_url(self): - return self.resolve_url(ACTION_LIST, args=(self.kwargs['pk'],)) - - @property - def create_url(self): - return self.resolve_url(ACTION_CREATE, args=(self.kwargs['pk'],)) - - def get_context_data(self, **kwargs): - obj = getattr(self, 'object', None) - if obj: - root_pk = getattr(obj, self.crud.parent_field).pk - else: - root_pk = self.kwargs['pk'] # in list and create - kwargs.setdefault('root_pk', root_pk) - return super(MasterDetailCrud__OBSOLETO.BaseMixin, - self).get_context_data(**kwargs) - - class ListView(CrudListView): - - @classmethod - def get_url_regex(cls): - return r'^(?P\d+)/%s$' % cls.model._meta.model_name - - def get_queryset(self): - qs = super( - MasterDetailCrud__OBSOLETO.ListView, self).get_queryset() - kwargs = {self.crud.parent_field: self.kwargs['pk']} - return qs.filter(**kwargs) - - class CreateView(CrudCreateView): - - @classmethod - def get_url_regex(cls): - return r'^(?P\d+)/%s/create$' % cls.model._meta.model_name - - def get_form(self, form_class=None): - form = super(MasterDetailCrud__OBSOLETO.CreateView, - self).get_form(self.form_class) - field = self.model._meta.get_field(self.crud.parent_field) - parent = field.related_model.objects.get(pk=self.kwargs['pk']) - setattr(form.instance, self.crud.parent_field, parent) - return form - - class DetailView(CrudDetailView): - - @classmethod - def get_url_regex(cls): - return r'^%s/(?P\d+)$' % cls.model._meta.model_name - - class UpdateView(CrudUpdateView): - - @classmethod - def get_url_regex(cls): - return r'^%s/(?P\d+)/edit$' % cls.model._meta.model_name - - class DeleteView(CrudDeleteView): - - @classmethod - def get_url_regex(cls): - return r'^%s/(?P\d+)/delete$' % cls.model._meta.model_name - - def get_success_url(self): - pk = getattr(self.get_object(), self.crud.parent_field).pk - return self.resolve_url(ACTION_LIST, args=(pk,)) - - @classonlymethod - def build(cls, model, parent_field, help_path): - crud = super(MasterDetailCrud__OBSOLETO, cls).build(model, help_path) - crud.parent_field = parent_field - return crud diff --git a/sapl/crud/urls.py b/sapl/crud/urls.py index 53b6e36fa..8b7da50fe 100644 --- a/sapl/crud/urls.py +++ b/sapl/crud/urls.py @@ -1,13 +1,4 @@ -from builtins import LookupError - -from django import apps from django.conf.urls import include, url -from django.contrib.auth.management import _get_all_permissions -from django.core import exceptions -from django.db import models, router -from django.db.utils import DEFAULT_DB_ALIAS -from django.utils.translation import string_concat - urlpatterns = [ url(r'', include('stub_app.urls')), diff --git a/sapl/materia/models.py b/sapl/materia/models.py index 2e40cde6f..af7804ee9 100644 --- a/sapl/materia/models.py +++ b/sapl/materia/models.py @@ -6,8 +6,8 @@ from model_utils import Choices from sapl.comissoes.models import Comissao from sapl.parlamentares.models import Parlamentar, Partido from sapl.utils import (RANGE_ANOS, YES_NO_CHOICES, - restringe_tipos_de_arquivo_txt, xstr, - get_settings_auth_user_model) + get_settings_auth_user_model, + restringe_tipos_de_arquivo_txt, xstr) def grupo_autor(): diff --git a/sapl/materia/tests/test_materia.py b/sapl/materia/tests/test_materia.py index 953546c27..c7ca7d721 100644 --- a/sapl/materia/tests/test_materia.py +++ b/sapl/materia/tests/test_materia.py @@ -1,8 +1,8 @@ +import pytest from django.contrib.auth import get_user_model from django.core.files.uploadedfile import SimpleUploadedFile from django.core.urlresolvers import reverse from model_mommy import mommy -import pytest from sapl.comissoes.models import Comissao, TipoComissao from sapl.materia.models import (Anexada, Autor, Autoria, DespachoInicial, diff --git a/sapl/materia/views.py b/sapl/materia/views.py index 2e412c532..cee9abd19 100644 --- a/sapl/materia/views.py +++ b/sapl/materia/views.py @@ -28,7 +28,7 @@ from sapl.compilacao.views import IntegracaoTaView from sapl.crispy_layout_mixin import SaplFormLayout, form_actions, to_row from sapl.crud.base import (Crud, CrudBaseMixin, CrudCreateView, CrudDeleteView, CrudDetailView, CrudListView, - CrudUpdateView, make_pagination, MasterDetailCrud) + CrudUpdateView, MasterDetailCrud, make_pagination) from sapl.norma.models import LegislacaoCitada from sapl.utils import (TURNO_TRAMITACAO_CHOICES, YES_NO_CHOICES, autor_label, autor_modal, gerar_hash_arquivo, get_base_url, diff --git a/sapl/norma/views.py b/sapl/norma/views.py index 24a243e81..d2c461952 100644 --- a/sapl/norma/views.py +++ b/sapl/norma/views.py @@ -1,6 +1,5 @@ from datetime import datetime -from django.contrib.auth.mixins import PermissionRequiredMixin from django.shortcuts import redirect from django.views.generic import FormView, ListView diff --git a/sapl/protocoloadm/views.py b/sapl/protocoloadm/views.py index 45738735e..a02fec06e 100644 --- a/sapl/protocoloadm/views.py +++ b/sapl/protocoloadm/views.py @@ -1,5 +1,5 @@ -from datetime import date, datetime import json +from datetime import date, datetime from braces.views import FormValidMessageMixin, PermissionRequiredMixin from django.contrib import messages @@ -13,15 +13,14 @@ from django.views.generic import CreateView, DetailView, FormView, ListView from django.views.generic.base import TemplateView from django_filters.views import FilterView +import sapl.crud.base from sapl.base.models import AppConfig from sapl.crud.base import (Crud, CrudBaseMixin, CrudCreateView, - CrudDetailView, CrudDeleteView, - CrudListView, CrudUpdateView, - make_pagination, MasterDetailCrud) + CrudDeleteView, CrudDetailView, CrudListView, + CrudUpdateView, MasterDetailCrud, make_pagination) from sapl.materia.models import TipoMateriaLegislativa from sapl.utils import (create_barcode, get_client_ip, permissoes_adm, permissoes_protocoloadm) -import sapl.crud.base from .forms import (AnularProcoloAdmForm, DocumentoAcessorioAdministrativoForm, DocumentoAdministrativoFilterSet, @@ -34,7 +33,6 @@ from .models import (Autor, DocumentoAcessorioAdministrativo, TipoDocumentoAdministrativo, TipoInstituicao, TramitacaoAdministrativo) - TipoDocumentoAdministrativoCrud = Crud.build(TipoDocumentoAdministrativo, '') DocumentoAcessorioAdministrativoCrud = Crud.build( DocumentoAcessorioAdministrativo, '') diff --git a/sapl/sessao/views.py b/sapl/sessao/views.py index d950488cf..b23af488b 100644 --- a/sapl/sessao/views.py +++ b/sapl/sessao/views.py @@ -18,7 +18,7 @@ from rest_framework import generics from sapl.crud.base import (Crud, CrudBaseMixin, CrudCreateView, CrudDeleteView, CrudDetailView, CrudListView, - CrudUpdateView, make_pagination, MasterDetailCrud) + CrudUpdateView, MasterDetailCrud, make_pagination) from sapl.materia.forms import pega_ultima_tramitacao from sapl.materia.models import (Autoria, DocumentoAcessorio, TipoMateriaLegislativa, Tramitacao) @@ -42,7 +42,6 @@ from .models import (Bancada, Bloco, CargoBancada, CargoMesa, SessaoPlenariaPresenca, TipoExpediente, TipoResultadoVotacao, TipoSessaoPlenaria, VotoParlamentar) - OrdemDiaCrud = Crud.build(OrdemDia, '') RegistroVotacaoCrud = Crud.build(RegistroVotacao, '') diff --git a/sapl/utils.py b/sapl/utils.py index 4f7ec84f7..3b6d8b1f0 100644 --- a/sapl/utils.py +++ b/sapl/utils.py @@ -1,8 +1,9 @@ +import hashlib from datetime import date from functools import wraps from unicodedata import normalize as unicodedata_normalize -import hashlib +import magic from django import forms from django.apps import apps from django.conf import settings @@ -12,7 +13,6 @@ from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from floppyforms import ClearableFileInput -import magic def normalize(txt):