Browse Source

Aplica refatoração do crud na App Base

pull/675/head
LeandroRoberto 8 years ago
parent
commit
6ac0373093
  1. 6
      sapl/base/models.py
  2. 1
      sapl/base/templatetags/common_tags.py
  3. 1
      sapl/base/urls.py
  4. 66
      sapl/base/views.py
  5. 1
      sapl/comissoes/models.py
  6. 12
      sapl/comissoes/views.py
  7. 2
      sapl/crispy_layout_mixin.py
  8. 20
      sapl/crud/base.py
  9. 82
      sapl/crud/masterdetail.py
  10. 9
      sapl/crud/urls.py
  11. 4
      sapl/materia/models.py
  12. 2
      sapl/materia/tests/test_materia.py
  13. 2
      sapl/materia/views.py
  14. 1
      sapl/norma/views.py
  15. 10
      sapl/protocoloadm/views.py
  16. 3
      sapl/sessao/views.py
  17. 4
      sapl/utils.py

6
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')))

1
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):

1
sapl/base/urls.py

@ -12,7 +12,6 @@ from .views import (AppConfigCrud, CasaLegislativaCrud, HelpView,
RelatorioMateriasTramitacaoView,
RelatorioPresencaSessaoView)
app_name = AppConfig.name

66
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'))

1
sapl/comissoes/models.py

@ -1,4 +1,3 @@
import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _

12
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)

2
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):

20
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

82
sapl/crud/masterdetail.py

@ -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<pk>\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<pk>\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<pk>\d+)$' % cls.model._meta.model_name
class UpdateView(CrudUpdateView):
@classmethod
def get_url_regex(cls):
return r'^%s/(?P<pk>\d+)/edit$' % cls.model._meta.model_name
class DeleteView(CrudDeleteView):
@classmethod
def get_url_regex(cls):
return r'^%s/(?P<pk>\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

9
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')),

4
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():

2
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,

2
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,

1
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

10
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, '')

3
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, '')

4
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):

Loading…
Cancel
Save