From ae1149d936c95bd288209f021cd4db4cdd63eae5 Mon Sep 17 00:00:00 2001 From: Marcio Mazza Date: Fri, 19 Feb 2016 17:46:03 -0200 Subject: [PATCH 1/2] Refatora crud usando mixins MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Torna a api mais flexível. Onde antes estendíamos algumas CBVs diretamente agora usamos mixins. --- comissoes/views.py | 10 +- compilacao/views.py | 16 +- crud.py | 424 ++++++++++++++++++++++------------------ crud_tests/test_flux.py | 61 +++--- crud_tests/urls.py | 4 +- crud_tests/views.py | 12 +- lexml/views.py | 6 +- materia/views.py | 40 ++-- norma/views.py | 12 +- painel/views.py | 4 +- parlamentares/views.py | 28 +-- protocoloadm/views.py | 16 +- sessao/views.py | 16 +- 13 files changed, 355 insertions(+), 294 deletions(-) diff --git a/comissoes/views.py b/comissoes/views.py index 1151cdc9c..4ba30b38a 100644 --- a/comissoes/views.py +++ b/comissoes/views.py @@ -5,7 +5,7 @@ from django.views.generic import ListView from django.views.generic.edit import FormMixin from vanilla import GenericView -from crud import build_crud +from crud import Crud from materia.models import Tramitacao from parlamentares.models import Filiacao @@ -14,28 +14,28 @@ from .forms import (CadastrarComissaoForm, ComposicaoForm, from .models import (CargoComissao, Comissao, Composicao, Participacao, Periodo, TipoComissao) -cargo_crud = build_crud( +cargo_crud = Crud( CargoComissao, 'cargo_comissao', [ [_('Período de composição de Comissão'), [('nome', 10), ('unico', 2)]], ]) -periodo_composicao_crud = build_crud( +periodo_composicao_crud = Crud( Periodo, 'periodo_composicao_comissao', [ [_('Cargo de Comissão'), [('data_inicio', 6), ('data_fim', 6)]], ]) -tipo_comissao_crud = build_crud( +tipo_comissao_crud = Crud( TipoComissao, 'tipo_comissao', [ [_('Tipo Comissão'), [('nome', 9), ('sigla', 3)], [('dispositivo_regimental', 9), ('natureza', 3)]], ]) -comissao_crud = build_crud( +comissao_crud = Crud( Comissao, 'modulo_comissoes', [ [_('Dados Básicos'), diff --git a/compilacao/views.py b/compilacao/views.py index 4db80bda0..371696288 100644 --- a/compilacao/views.py +++ b/compilacao/views.py @@ -27,7 +27,7 @@ from compilacao.models import (Dispositivo, Nota, TextoArticulado, TipoDispositivo, TipoNota, TipoPublicacao, TipoTextoArticulado, TipoVide, VeiculoPublicacao, Vide) -from crud import NO_ENTRIES_MSG, build_crud, make_pagination +from crud import Crud, CrudListMixin, make_pagination DISPOSITIVO_SELECT_RELATED = ( 'tipo_dispositivo', @@ -42,7 +42,7 @@ DISPOSITIVO_SELECT_RELATED = ( 'ta_publicado', 'ta',) -tipo_nota_crud = build_crud( +tipo_nota_crud = Crud( TipoNota, 'tipo_nota', [ [_('Tipo da Nota'), @@ -50,14 +50,14 @@ tipo_nota_crud = build_crud( [('modelo', 12)]], ]) -tipo_vide_crud = build_crud( +tipo_vide_crud = Crud( TipoVide, 'tipo_vide', [ [_('Tipo de Vide'), [('sigla', 2), ('nome', 10)]], ]) -tipo_publicacao_crud = build_crud( +tipo_publicacao_crud = Crud( TipoPublicacao, 'tipo_publicacao', [ [_('Tipo de Publicação'), @@ -65,7 +65,7 @@ tipo_publicacao_crud = build_crud( ]) -veiculo_publicacao_crud = build_crud( +veiculo_publicacao_crud = Crud( VeiculoPublicacao, 'veiculo_publicacao', [ [_('Veículo de Publicação'), @@ -73,7 +73,7 @@ veiculo_publicacao_crud = build_crud( ]) -perfil_estr_txt_norm = build_crud( +perfil_estr_txt_norm = Crud( PerfilEstruturalTextoArticulado, 'perfil_estrutural', [ [_('Perfil Estrutural de Textos Articulados'), @@ -81,7 +81,7 @@ perfil_estr_txt_norm = build_crud( ]) -tipo_dispositivo_crud = build_crud( +tipo_dispositivo_crud = Crud( TipoDispositivo, 'tipo_dispositivo', [ [_('Dados Básicos'), @@ -1740,7 +1740,7 @@ class PublicacaoListView(ListView): def get_context_data(self, **kwargs): context = super(PublicacaoListView, self).get_context_data(**kwargs) - context['NO_ENTRIES_MSG'] = NO_ENTRIES_MSG + context['NO_ENTRIES_MSG'] = CrudListMixin.no_entries_msg return context diff --git a/crud.py b/crud.py index 97a38dd24..6bd7855e2 100644 --- a/crud.py +++ b/crud.py @@ -2,16 +2,13 @@ from braces.views import FormMessagesMixin from crispy_forms.helper import FormHelper from django import forms from django.conf.urls import url -from django.core.urlresolvers import reverse, reverse_lazy -from django.utils.functional import cached_property +from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from django.views.generic import (CreateView, DeleteView, DetailView, ListView, UpdateView) from sapl.layout import SaplFormLayout -NO_ENTRIES_MSG = _('Não existem registros') - def from_to(start, end): return list(range(start, end + 1)) @@ -51,199 +48,248 @@ def get_field_display(obj, fieldname): value = getattr(obj, 'get_%s_display' % fieldname)() else: value = getattr(obj, fieldname) - if value is None: display = '' elif 'date' in str(type(value)): - display = value.strftime("%d/%m/%Y") + display = value.strftime("%d/%m/%Y") # TODO: localize elif 'bool' in str(type(value)): display = 'Sim' if value else 'Não' else: display = str(value) - return verbose_name, display +class CrispyLayoutFormMixin(object): + + def get_form_class(self): + + layout = self.layout + + class CrispyForm(forms.ModelForm): + + class Meta: + model = self.model + exclude = [] + + def __init__(self, *args, **kwargs): + super(CrispyForm, self).__init__(*args, **kwargs) + self.helper = FormHelper() + self.helper.layout = SaplFormLayout(*layout) + + return CrispyForm + + @property + def list_field_names(self): + '''The list of field names to display on table + + This base implementation returns the field names + in the first fieldset of the layout. + ''' + rows = self.layout[0][1:] + return [fieldname for row in rows for fieldname, __ in row] + + def get_column(self, fieldname, span): + obj = self.get_object() + verbose_name, text = get_field_display(obj, fieldname) + return { + 'id': fieldname, + 'span': span, + 'verbose_name': verbose_name, + 'text': text, + } + + @property + def fieldsets(self): + return [ + {'legend': legend, + 'rows': [[self.get_column(fieldname, span) + for fieldname, span in row] + for row in rows] + } for legend, *rows in self.layout] + + +class BaseCrudMixin(CrispyLayoutFormMixin): + + @property + def namespace(self): + return self.model._meta.model_name + + def resolve_url(self, url_name, args=None): + return reverse('%s:%s' % (self.namespace, url_name), args=args) + + @property + def list_url(self): + return self.resolve_url('list') + + @property + def create_url(self): + return self.resolve_url('create') + + @property + def detail_url(self): + return self.resolve_url('detail', args=(self.object.id,)) + + @property + def update_url(self): + return self.resolve_url('update', args=(self.object.id,)) + + @property + def delete_url(self): + return self.resolve_url('delete', args=(self.object.id,)) + + def get_template_names(self): + names = super(BaseCrudMixin, self).get_template_names() + names.append("crud/%s.html" % + self.template_name_suffix.lstrip('_')) + return names + + @property + def verbose_name(self): + return self.model._meta.verbose_name + + @property + def verbose_name_plural(self): + return self.model._meta.verbose_name_plural + + +class CrudListMixin(): + + paginate_by = 10 + no_entries_msg = _('Nenhum registro encontrado.') + + @property + def title(self): + return self.verbose_name_plural + + def _as_row(self, obj): + return [ + (get_field_display(obj, name)[1], obj.pk if i == 0 else None) + for i, name in enumerate(self.list_field_names)] + + def get_context_data(self, **kwargs): + context = super(CrudListMixin, self).get_context_data(**kwargs) + + # pagination + page_obj = context['page_obj'] + paginator = context['paginator'] + context['page_range'] = make_pagination( + page_obj.number, paginator.num_pages) + + # rows + object_list = context['object_list'] + context['rows'] = [self._as_row(obj) for obj in object_list] + + context['headers'] = [ + self.model._meta.get_field(fieldname).verbose_name + for fieldname in self.list_field_names] + context['NO_ENTRIES_MSG'] = self.no_entries_msg + + return context + + +def make_form_invalid_message(msg): + return '%s %s' % (_('Formulário inválido.'), msg) + + +class CrudCreateMixin(FormMessagesMixin): + + form_valid_message = _('Registro criado com sucesso!') + form_invalid_message = make_form_invalid_message( + _('O registro não foi criado.')) + + @property + def title(self): + return _('Adicionar %(verbose_name)s') % { + 'verbose_name': self.verbose_name} + + @property + def cancel_url(self): + return self.list_url + + def get_success_url(self): + return self.detail_url + + +class CrudDetailMixin(): + + @property + def title(self): + # TODO: can we just use view.object in the templates???? + return str(self.object) + + +class CrudUpdateMixin(FormMessagesMixin): + + form_valid_message = _('Registro alterado com sucesso!') + form_invalid_message = make_form_invalid_message( + _('Suas alterações não foram salvas.')) + + @property + def title(self): + return str(self.object) + + @property + def cancel_url(self): + return self.detail_url + + def get_success_url(self): + return self.detail_url + + +class CrudDeleteMixin(FormMessagesMixin): + + form_valid_message = _('Registro excluído com sucesso!') + form_invalid_message = make_form_invalid_message( + _('O registro não foi excluído.')) + + def get_success_url(self): + return self.list_url + + class Crud(object): - pass - - -def build_crud(model, help_path, layout): - crud = Crud() - crud.model = model - crud.help_path = help_path - crud.namespace = model._meta.model_name - - class CrispyForm(forms.ModelForm): - - class Meta: - model = crud.model - exclude = [] - - def __init__(self, *args, **kwargs): - super(CrispyForm, self).__init__(*args, **kwargs) - self.helper = FormHelper() - self.helper.layout = SaplFormLayout(*layout) - - crud.model_form = CrispyForm - - def in_namespace(url_name): - return '%s:%s' % (crud.namespace, url_name) - - def make_form_invalid_message(msg): - return '%s %s' % (_('Formulário inválido.'), msg) - - class BaseMixin(object): - model = crud.model - - verbose_name = crud.model._meta.verbose_name - verbose_name_plural = crud.model._meta.verbose_name_plural - - list_url = reverse_lazy(in_namespace('list')) - create_url = reverse_lazy(in_namespace('create')) - help_path = crud.help_path # FIXME - - def get_url_for_this_object(self, url_name): - return reverse(in_namespace(url_name), args=(self.object.id,)) - - @property - def detail_url(self): - return self.get_url_for_this_object('detail') - - @property - def update_url(self): - return self.get_url_for_this_object('update') - - @property - def delete_url(self): - return self.get_url_for_this_object('delete') - - def get_template_names(self): - names = super(BaseMixin, self).get_template_names() - names.append("crud/%s.html" % - self.template_name_suffix.lstrip('_')) - return names - - class CrudListView(BaseMixin, ListView): - title = BaseMixin.verbose_name_plural - paginate_by = 10 - no_entries_msg = NO_ENTRIES_MSG - - @cached_property - def field_names(self): - '''The list of field names to display on table - - This base implementation returns the field names - in the first fieldset of the layout. - ''' - rows = layout[0][1:] - return [fieldname for row in rows for fieldname, __ in row] - - def get_rows(self, object_list): - return [[(get_field_display(obj, name)[1], - obj.pk if i == 0 else None) - for i, name in enumerate(self.field_names)] - for obj in object_list - ] - - def get_context_data(self, **kwargs): - context = super(CrudListView, self).get_context_data(**kwargs) - paginator = context['paginator'] - page_obj = context['page_obj'] - context['page_range'] = make_pagination( - page_obj.number, paginator.num_pages) - object_list = context['object_list'] - context['headers'] = [ - self.model._meta.get_field(fieldname).verbose_name - for fieldname in self.field_names] - context['rows'] = self.get_rows(object_list) - context['NO_ENTRIES_MSG'] = NO_ENTRIES_MSG - return context - - class CrudCreateView(BaseMixin, FormMessagesMixin, CreateView): - form_class = crud.model_form - title = _('Adicionar %(verbose_name)s') % { - 'verbose_name': BaseMixin.verbose_name} - form_valid_message = _('Registro criado com sucesso!') - form_invalid_message = make_form_invalid_message( - _('O registro não foi criado.')) - cancel_url = BaseMixin.list_url - - def form_invalid(self, form): - """ - If the form is invalid, re-render the context data with the - data-filled form and errors. - """ - return self.render_to_response(self.get_context_data(form=form)) - - def get_success_url(self): - return self.detail_url - - class CrudDetailView(BaseMixin, DetailView): - - @property - def title(self): - return self.get_object() - - def get_column(self, fieldname, span): - obj = self.get_object() - verbose_name, text = get_field_display(obj, fieldname) - return { - 'id': fieldname, - 'span': span, - 'verbose_name': verbose_name, - 'text': text, - } - - @property - def fieldsets(self): - return [ - {'legend': legend, - 'rows': [[self.get_column(fieldname, span) - for fieldname, span in row] - for row in rows] - } for legend, *rows in layout] - - class CrudUpdateView(BaseMixin, FormMessagesMixin, UpdateView): - form_class = crud.model_form - form_valid_message = _('Registro alterado com sucesso!') - form_invalid_message = make_form_invalid_message( - _('Suas alterações não foram salvas.')) - - @property - def title(self): - return self.get_object() - - def get_success_url(self): - return self.detail_url - - def cancel_url(self): - return self.detail_url - - class CrudDeleteView(BaseMixin, FormMessagesMixin, DeleteView): - form_valid_message = _('Registro excluído com sucesso!') - form_invalid_message = make_form_invalid_message( - _('O registro não foi excluído.')) - - def get_success_url(self): - return self.list_url - - crud.CrudListView = CrudListView - crud.CrudCreateView = CrudCreateView - crud.CrudDetailView = CrudDetailView - crud.CrudUpdateView = CrudUpdateView - crud.CrudDeleteView = CrudDeleteView - - # XXX transform into a property of Crud to enable override - crud.urlpatterns = [ - url(r'^$', CrudListView.as_view(), name='list'), - url(r'^create$', CrudCreateView.as_view(), name='create'), - url(r'^(?P\d+)$', CrudDetailView.as_view(), name='detail'), - url(r'^(?P\d+)/edit$', - CrudUpdateView.as_view(), name='update'), - url(r'^(?P\d+)/delete$', - CrudDeleteView.as_view(), name='delete'), - ] - crud.urls = crud.urlpatterns, crud.namespace, crud.namespace - - return crud + + def __init__(self, model, help_path, layout, + crud_mixin=BaseCrudMixin, + crud_list_mixin=CrudListMixin, + crud_create_mixin=CrudCreateMixin, + crud_detail_mixin=CrudDetailMixin, + crud_update_mixin=CrudUpdateMixin, + crud_delete_mixin=CrudDeleteMixin, + ): + + class CrudMixin(crud_mixin): + pass + CrudMixin.model = model + CrudMixin.help_path = help_path + CrudMixin.layout = layout + + class CrudListView(CrudMixin, crud_list_mixin, ListView): + pass + + class CrudCreateView(CrudMixin, crud_create_mixin, CreateView): + pass + + class CrudDetailView(CrudMixin, crud_detail_mixin, DetailView): + pass + + class CrudUpdateView(CrudMixin, crud_update_mixin, UpdateView): + pass + + class CrudDeleteView(CrudMixin, crud_delete_mixin, DeleteView): + pass + + self.urlpatterns = [ + url(r'^$', CrudListView.as_view(), name='list'), + url(r'^create$', CrudCreateView.as_view(), name='create'), + url(r'^(?P\d+)$', CrudDetailView.as_view(), name='detail'), + url(r'^(?P\d+)/edit$', + CrudUpdateView.as_view(), name='update'), + url(r'^(?P\d+)/delete$', + CrudDeleteView.as_view(), name='delete'), + ] + + self.namespace = CrudMixin().namespace + self.urls = self.urlpatterns, self.namespace, self.namespace + + # FIXME Refatorar código que precisa desse atributo e remover + self.CrudDetailView = CrudDetailView diff --git a/crud_tests/test_flux.py b/crud_tests/test_flux.py index 47603c952..4bca1943b 100644 --- a/crud_tests/test_flux.py +++ b/crud_tests/test_flux.py @@ -2,29 +2,15 @@ import pytest from django.core.urlresolvers import reverse from model_mommy import mommy -from crud import (NO_ENTRIES_MSG, build_crud, from_to, get_field_display, - make_pagination) +from crud import (CrispyLayoutFormMixin, CrudListMixin, from_to, + get_field_display, make_pagination) from .models import Continent, Country -from .views import country_crud +from .views import CountryCrudListMixin pytestmark = pytest.mark.django_db -@pytest.mark.parametrize("layout, result", [ - ([['Dados Complementares']], []), # missing rows definition - - ([['Basic', [('name', 9), ('population', 3)]], - ['More Details', [('description', 12)]], - ], - ['name', 'population']), -]) -def test_listview_get_fieldnames(layout, result): - crud = build_crud(Country, 'stub_help_path', layout) - view = crud.CrudListView() - assert view.field_names == result - - __ = None # for test readability @@ -82,21 +68,46 @@ def test_get_field_display(): assert get_field_display(stub, 'population')[1] == '' -def test_crud_detail_view_fieldsets(monkeypatch): +@pytest.mark.parametrize("_layout, result", [ + ([['Dados Complementares']], []), # missing rows definition + + ([['Basic', [('name', 9), ('population', 3)]], + ['More Details', [('description', 12)]], + ], + ['name', 'population']), +]) +def test_layout_fieldnames(_layout, result): + + class StubMixin(CrispyLayoutFormMixin): + layout = _layout + + view = StubMixin() + assert view.list_field_names == result + + +def test_layout_detail_fieldsets(monkeypatch): - view = country_crud.CrudDetailView() stub = mommy.make(Country, name='Brazil', continent__name='South America', is_cold=False) + class StubMixin(CrispyLayoutFormMixin): + layout = [['Basic Data', + [('name', 9), ('continent', 3)], + [('population', 6), ('is_cold', 6)] + ], + ['More Details', [('description', 12)]], + ] + + def get_object(self): + return stub + + view = StubMixin() + # to test None displayed as empty string assert stub.population is None - def get_object(): - return stub - monkeypatch.setattr(view, 'get_object', get_object) - assert view.fieldsets == [ {'legend': 'Basic Data', 'rows': [[{'id': 'name', @@ -136,7 +147,7 @@ def assert_h1(res, title): assert res.html.find('main').find('h1').text == title -NO_ENTRIES_MSG = str(NO_ENTRIES_MSG) # "unlazy" +NO_ENTRIES_MSG = str(CrudListMixin.no_entries_msg) # "unlazy" def assert_on_list_page(res): @@ -181,7 +192,7 @@ def test_flux_list_paginate_detail( population=population, is_cold=is_cold) - country_crud.CrudListView.paginate_by = page_size + CountryCrudListMixin.paginate_by = page_size res = app.get('/countries/') diff --git a/crud_tests/urls.py b/crud_tests/urls.py index b9ba39d7c..94880e39e 100644 --- a/crud_tests/urls.py +++ b/crud_tests/urls.py @@ -3,7 +3,5 @@ from django.conf.urls import include, url from .views import country_crud urlpatterns = [ - url(r'^countries/', include(country_crud.urlpatterns, - country_crud.namespace, - country_crud.namespace)), + url(r'^countries/', include(country_crud.urls)), ] diff --git a/crud_tests/views.py b/crud_tests/views.py index 72393388a..9255c1938 100644 --- a/crud_tests/views.py +++ b/crud_tests/views.py @@ -1,12 +1,18 @@ -from crud import build_crud +from crud import Crud, CrudListMixin from .models import Country -country_crud = build_crud( + +class CountryCrudListMixin(CrudListMixin): + paginate_by = 10 + + +country_crud = Crud( Country, 'help_path', [ ['Basic Data', [('name', 9), ('continent', 3)], [('population', 6), ('is_cold', 6)] ], ['More Details', [('description', 12)]], - ]) + ], + crud_list_mixin=CountryCrudListMixin) diff --git a/lexml/views.py b/lexml/views.py index b9f0b5a31..e75ef2db9 100644 --- a/lexml/views.py +++ b/lexml/views.py @@ -1,10 +1,10 @@ from django.utils.translation import ugettext_lazy as _ -from crud import build_crud +from crud import Crud from .models import LexmlProvedor, LexmlPublicador -lexml_provedor_crud = build_crud( +lexml_provedor_crud = Crud( LexmlProvedor, 'lexml_provedor', [ [_('Provedor Lexml'), @@ -16,7 +16,7 @@ lexml_provedor_crud = build_crud( ]) -lexml_publicador_crud = build_crud( +lexml_publicador_crud = Crud( LexmlPublicador, 'lexml_publicador', [ [_('Publicador Lexml'), diff --git a/materia/views.py b/materia/views.py index cfce6e8cd..6b9c83674 100644 --- a/materia/views.py +++ b/materia/views.py @@ -14,7 +14,7 @@ from vanilla.views import GenericView from comissoes.models import Comissao, Composicao from compilacao.views import IntegracaoTaView -from crud import build_crud, make_pagination +from crud import Crud, make_pagination from norma.models import LegislacaoCitada, NormaJuridica, TipoNormaJuridica from parlamentares.models import Partido from sessao.models import AcompanharMateria @@ -31,42 +31,42 @@ from .models import (Anexada, Autor, Autoria, DespachoInicial, TipoFimRelatoria, TipoMateriaLegislativa, TipoProposicao, Tramitacao, UnidadeTramitacao) -origem_crud = build_crud( +origem_crud = Crud( Origem, 'origem', [ [_('Origem'), [('nome', 8), ('sigla', 4)]], ]) -tipo_materia_crud = build_crud( +tipo_materia_crud = Crud( TipoMateriaLegislativa, 'tipo_materia_legislativa', [ [_('Tipo Matéria Legislativa'), [('sigla', 4), ('descricao', 8)]], ]) -regime_tramitacao_crud = build_crud( +regime_tramitacao_crud = Crud( RegimeTramitacao, 'regime_tramitacao', [ [_('Tipo de Documento'), [('descricao', 12)]], ]) -tipo_documento_crud = build_crud( +tipo_documento_crud = Crud( TipoDocumento, 'tipo_documento', [ [_('Regime Tramitação'), [('descricao', 12)]], ]) -tipo_fim_relatoria_crud = build_crud( +tipo_fim_relatoria_crud = Crud( TipoFimRelatoria, 'fim_relatoria', [ [_('Tipo Fim de Relatoria'), [('descricao', 12)]], ]) -materia_legislativa_crud = build_crud( +materia_legislativa_crud = Crud( MateriaLegislativa, '', [ [_('Identificação Básica'), @@ -95,7 +95,7 @@ materia_legislativa_crud = build_crud( [('observacao', 12)]], ]) -Anexada_crud = build_crud( +Anexada_crud = Crud( Anexada, '', [ [_('Matéria Legislativa'), @@ -111,14 +111,14 @@ Anexada_crud = build_crud( [('data_anexacao', 6), ('data_desanexacao', 6)]], ]) -tipo_autor_crud = build_crud( +tipo_autor_crud = Crud( TipoAutor, 'tipo_autor', [ [_('Tipo Autor'), [('descricao', 12)]], ]) -autor_crud = build_crud( +autor_crud = Crud( Autor, 'autor', [ [_('Autor'), @@ -126,7 +126,7 @@ autor_crud = build_crud( [('username', 12)]], ]) -autoria_crud = build_crud( +autoria_crud = Crud( Autoria, '', [ [_('Autoria'), @@ -135,7 +135,7 @@ autoria_crud = build_crud( ('primeiro_autor', 4)]], ]) -documento_acessorio_crud = build_crud( +documento_acessorio_crud = Crud( DocumentoAcessorio, '', [ [_('Documento Acessório'), @@ -146,7 +146,7 @@ documento_acessorio_crud = build_crud( [('txt_observacao_FIXME', 12)]], ]) -numeracao_crud = build_crud( +numeracao_crud = Crud( Numeracao, '', [ [_('Numeração'), @@ -154,7 +154,7 @@ numeracao_crud = build_crud( [('ano_materia', 6), ('data_materia', 6)]], ]) -orgao_crud = build_crud( +orgao_crud = Crud( Orgao, 'orgao', [ [_('Órgão'), @@ -165,7 +165,7 @@ orgao_crud = build_crud( ('unidade_deliberativa', 2)]], ]) -relatoria_crud = build_crud( +relatoria_crud = Crud( Relatoria, '', [ [_('Relatoria'), @@ -174,7 +174,7 @@ relatoria_crud = build_crud( [('data_destituicao_relator', 6), ('tipo_fim_relatoria', 6)]], ]) -tipo_proposicao_crud = build_crud( +tipo_proposicao_crud = Crud( TipoProposicao, 'tipo_proposicao', [ [_('Tipo Proposição'), @@ -183,7 +183,7 @@ tipo_proposicao_crud = build_crud( [('modelo', 12)]], ]) -proposicao_crud = build_crud( +proposicao_crud = Crud( Proposicao, '', [ [_('Proposição'), @@ -195,7 +195,7 @@ proposicao_crud = build_crud( [('nom_arquivo_FIXME', 6), ('modelo_FIXME', 6)]], ]) -status_tramitacao_crud = build_crud( +status_tramitacao_crud = Crud( StatusTramitacao, 'status_tramitacao', [ [_('Status Tramitação'), @@ -204,7 +204,7 @@ status_tramitacao_crud = build_crud( ('descricao', 7)]], ]) -unidade_tramitacao_crud = build_crud( +unidade_tramitacao_crud = Crud( UnidadeTramitacao, 'unidade_tramitacao', [ [_('Unidade Tramitação'), @@ -213,7 +213,7 @@ unidade_tramitacao_crud = build_crud( [('parlamentar', 12)]], ]) -tramitacao_crud = build_crud( +tramitacao_crud = Crud( Tramitacao, '', [ [_('Tramitação'), diff --git a/norma/views.py b/norma/views.py index 73ea3206b..02651ed51 100644 --- a/norma/views.py +++ b/norma/views.py @@ -8,21 +8,21 @@ from django.views.generic.edit import FormMixin from vanilla.views import GenericView from compilacao.views import IntegracaoTaView -from crud import build_crud +from crud import Crud from materia.models import MateriaLegislativa, TipoMateriaLegislativa from .forms import NormaJuridicaForm from .models import (AssuntoNorma, LegislacaoCitada, NormaJuridica, TipoNormaJuridica) -assunto_norma_crud = build_crud( +assunto_norma_crud = Crud( AssuntoNorma, 'assunto_norma_juridica', [ [_('Assunto Norma Jurídica'), [('assunto', 6), ('descricao', 6)]], ]) -tipo_norma_crud = build_crud( +tipo_norma_crud = Crud( TipoNormaJuridica, 'tipo_norma_juridica', [ [_('Tipo Norma Jurídica'), @@ -31,7 +31,7 @@ tipo_norma_crud = build_crud( ('equivalente_lexml', 4)]], ]) -norma_crud = build_crud( +norma_crud = Crud( NormaJuridica, '', [ @@ -51,7 +51,7 @@ norma_crud = build_crud( [('observacao', 12)]], ]) -norma_temporario_crud = build_crud( +norma_temporario_crud = Crud( NormaJuridica, 'normajuridica', [ [_('Identificação Básica'), @@ -60,7 +60,7 @@ norma_temporario_crud = build_crud( ]) -legislacao_citada_crud = build_crud( +legislacao_citada_crud = Crud( LegislacaoCitada, '', [ [_('Legislação Citada'), diff --git a/painel/views.py b/painel/views.py index 0c280cfb5..7483205a2 100644 --- a/painel/views.py +++ b/painel/views.py @@ -5,7 +5,7 @@ from django.http import HttpResponse, JsonResponse from django.shortcuts import render from django.utils.translation import ugettext_lazy as _ -from crud import build_crud +from crud import Crud from painel.models import Painel from parlamentares.models import Filiacao from sessao.models import (ExpedienteMateria, OrdemDia, PresencaOrdemDia, @@ -14,7 +14,7 @@ from sessao.models import (ExpedienteMateria, OrdemDia, PresencaOrdemDia, from .models import Cronometro -cronometro_painel_crud = build_crud( +cronometro_painel_crud = Crud( Cronometro, '', [ [_('Cronometro'), diff --git a/parlamentares/views.py b/parlamentares/views.py index 1e29eed53..788567036 100644 --- a/parlamentares/views.py +++ b/parlamentares/views.py @@ -11,7 +11,7 @@ from django.utils.translation import ugettext_lazy as _ from django.views.generic.edit import FormMixin from vanilla import GenericView -from crud import build_crud +from crud import Crud from .forms import (DependenteEditForm, DependenteForm, FiliacaoEditForm, FiliacaoForm, MandatoEditForm, MandatoForm, @@ -22,7 +22,7 @@ from .models import (CargoMesa, Coligacao, ComposicaoMesa, Dependente, Parlamentar, Partido, SessaoLegislativa, SituacaoMilitar, TipoAfastamento, TipoDependente) -cargo_mesa_crud = build_crud( +cargo_mesa_crud = Crud( CargoMesa, 'cargo_mesa', [ [_('Cargo na Mesa'), @@ -30,14 +30,14 @@ cargo_mesa_crud = build_crud( ('unico', 2)]], ]) -legislatura_crud = build_crud( +legislatura_crud = Crud( Legislatura, 'tabelas_auxiliares#legislatura', [ [_('Legislatura'), [('data_inicio', 4), ('data_fim', 4), ('data_eleicao', 4)]], ]) -coligacao_crud = build_crud( +coligacao_crud = Crud( Coligacao, 'coligacao', [ [_('Coligação'), @@ -46,7 +46,7 @@ coligacao_crud = build_crud( ('numero_votos', 2)]], ]) -partido_crud = build_crud( +partido_crud = Crud( Partido, 'partidos', [ [_('Partido Político'), @@ -57,7 +57,7 @@ partido_crud = build_crud( ]) -dependente_crud = build_crud( +dependente_crud = Crud( Dependente, '', [ [_('Dependentes'), @@ -67,7 +67,7 @@ dependente_crud = build_crud( ]) -sessao_legislativa_crud = build_crud( +sessao_legislativa_crud = Crud( SessaoLegislativa, 'sessao_legislativa', [ [_('Sessão Legislativa'), @@ -81,7 +81,7 @@ sessao_legislativa_crud = build_crud( ]) -parlamentar_crud = build_crud( +parlamentar_crud = Crud( Parlamentar, '', [ [_('Cadastro do Parlamentar'), @@ -101,14 +101,14 @@ parlamentar_crud = build_crud( [('biografia', 12)]], ]) -filiacao_crud = build_crud( +filiacao_crud = Crud( Filiacao, '', [ [_('Filiações Partidárias '), [('partido', 4), ('data', 4), ('data_desfiliacao', 4)]], ]) -mandato_crud = build_crud( +mandato_crud = Crud( Mandato, '', [ [_('Mandato'), @@ -120,28 +120,28 @@ mandato_crud = build_crud( [('observacao', 12)]], ]) -tipo_dependente_crud = build_crud( +tipo_dependente_crud = Crud( TipoDependente, 'tipo_dependente', [ [_('Tipo de Dependente'), [('descricao', 12)]], ]) -nivel_instrucao_crud = build_crud( +nivel_instrucao_crud = Crud( NivelInstrucao, 'nivel_instrucao', [ [_('Nível Instrução'), [('descricao', 12)]], ]) -tipo_afastamento_crud = build_crud( +tipo_afastamento_crud = Crud( TipoAfastamento, 'tipo_afastamento', [ [_('Tipo de Afastamento'), [('descricao', 5), ('dispositivo', 5), ('afastamento', 2)]], ]) -tipo_militar_crud = build_crud( +tipo_militar_crud = Crud( SituacaoMilitar, 'tipo_situa_militar', [ [_('Tipo Situação Militar'), diff --git a/protocoloadm/views.py b/protocoloadm/views.py index 14fe3eb40..1d09b7ce0 100644 --- a/protocoloadm/views.py +++ b/protocoloadm/views.py @@ -14,7 +14,7 @@ from django.views.generic.base import TemplateView from django.views.generic.edit import FormMixin from vanilla import GenericView -from crud import build_crud, make_pagination +from crud import Crud, make_pagination from materia.models import Proposicao, TipoMateriaLegislativa from sapl.utils import create_barcode @@ -27,14 +27,14 @@ from .models import (Autor, DocumentoAcessorioAdministrativo, StatusTramitacaoAdministrativo, TipoDocumentoAdministrativo, TramitacaoAdministrativo) -tipo_documento_administrativo_crud = build_crud( +tipo_documento_administrativo_crud = Crud( TipoDocumentoAdministrativo, '', [ [_('Tipo Documento Administrativo'), [('sigla', 4), ('descricao', 8)]], ]) -documento_administrativo_crud = build_crud( +documento_administrativo_crud = Crud( DocumentoAdministrativo, '', [ [_('Indentificação Básica'), @@ -49,7 +49,7 @@ documento_administrativo_crud = build_crud( [('observacao', 12)]], ]) -documento_acessorio_administrativo_crud = build_crud( +documento_acessorio_administrativo_crud = Crud( DocumentoAcessorioAdministrativo, '', [ [_('Documento Acessório'), @@ -59,7 +59,7 @@ documento_acessorio_administrativo_crud = build_crud( [('assunto', 12)]], ]) -status_tramitacao_administrativo_crud = build_crud( +status_tramitacao_administrativo_crud = Crud( StatusTramitacaoAdministrativo, '', [ [_('Status Tramitação Administrativo'), @@ -68,7 +68,7 @@ status_tramitacao_administrativo_crud = build_crud( ('descricao', 7)]], ]) -tramitacao_administrativo_crud = build_crud( +tramitacao_administrativo_crud = Crud( TramitacaoAdministrativo, '', [ [_('Tramitação'), @@ -78,7 +78,7 @@ tramitacao_administrativo_crud = build_crud( [('texto', 12)]], ]) -protocolo_documento_crud = build_crud( +protocolo_documento_crud = Crud( Protocolo, '', [ [_('Indentificação Documento'), @@ -89,7 +89,7 @@ protocolo_documento_crud = build_crud( [('observacao', 12)]], ]) -protocolo_materia_crud = build_crud( +protocolo_materia_crud = Crud( Protocolo, '', [ [_('Indentificação da Matéria'), diff --git a/sessao/views.py b/sessao/views.py index a4a815da5..5eb0e6924 100644 --- a/sessao/views.py +++ b/sessao/views.py @@ -10,7 +10,7 @@ from django.views.generic import ListView from django.views.generic.edit import FormMixin from rest_framework import generics -from crud import build_crud, make_pagination +from crud import Crud, make_pagination from materia.models import (Autoria, DocumentoAcessorio, TipoMateriaLegislativa, Tramitacao) from norma.models import NormaJuridica @@ -28,14 +28,14 @@ from .models import (AcompanharMateria, CargoMesa, ExpedienteMateria, TipoExpediente, TipoResultadoVotacao, TipoSessaoPlenaria, VotoParlamentar) -tipo_sessao_crud = build_crud( +tipo_sessao_crud = Crud( TipoSessaoPlenaria, 'tipo_sessao_plenaria', [ [_('Tipo de Sessão Plenária'), [('nome', 6), ('quorum_minimo', 6)]], ]) -sessao_crud = build_crud( +sessao_crud = Crud( SessaoPlenaria, '', [ [_('Dados Básicos'), @@ -49,7 +49,7 @@ sessao_crud = build_crud( [('url_audio', 6), ('url_video', 6)]], ]) -expediente_materia_crud = build_crud( +expediente_materia_crud = Crud( ExpedienteMateria, '', [ [_('Cadastro de Matérias do Expediente'), @@ -61,7 +61,7 @@ expediente_materia_crud = build_crud( [('observacao', 12)]], ]) -ordem_dia_crud = build_crud( +ordem_dia_crud = Crud( OrdemDia, '', [ [_('Cadastro de Matérias da Ordem do Dia'), @@ -73,21 +73,21 @@ ordem_dia_crud = build_crud( [('observacao', 12)]], ]) -tipo_resultado_votacao_crud = build_crud( +tipo_resultado_votacao_crud = Crud( TipoResultadoVotacao, 'tipo_resultado_votacao', [ [_('Tipo de Resultado da Votação'), [('nome', 12)]], ]) -tipo_expediente_crud = build_crud( +tipo_expediente_crud = Crud( TipoExpediente, 'tipo_expediente', [ [_('Tipo de Expediente'), [('nome', 12)]], ]) -registro_votacao_crud = build_crud( +registro_votacao_crud = Crud( RegistroVotacao, '', [ [_('Votação Simbólica'), From bec5d123caa336e03896bde54beb565d5dfde6dc Mon Sep 17 00:00:00 2001 From: Marcio Mazza Date: Thu, 25 Feb 2016 09:55:51 -0300 Subject: [PATCH 2/2] Simplifica nome de parametros do Crud --- crud.py | 27 +++++++++++++-------------- crud_tests/views.py | 2 +- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/crud.py b/crud.py index 6bd7855e2..80a2cff5b 100644 --- a/crud.py +++ b/crud.py @@ -249,33 +249,32 @@ class CrudDeleteMixin(FormMessagesMixin): class Crud(object): def __init__(self, model, help_path, layout, - crud_mixin=BaseCrudMixin, - crud_list_mixin=CrudListMixin, - crud_create_mixin=CrudCreateMixin, - crud_detail_mixin=CrudDetailMixin, - crud_update_mixin=CrudUpdateMixin, - crud_delete_mixin=CrudDeleteMixin, - ): - - class CrudMixin(crud_mixin): + base_mixin=BaseCrudMixin, + list_mixin=CrudListMixin, + create_mixin=CrudCreateMixin, + detail_mixin=CrudDetailMixin, + update_mixin=CrudUpdateMixin, + delete_mixin=CrudDeleteMixin): + + class CrudMixin(base_mixin): pass CrudMixin.model = model CrudMixin.help_path = help_path CrudMixin.layout = layout - class CrudListView(CrudMixin, crud_list_mixin, ListView): + class CrudListView(CrudMixin, list_mixin, ListView): pass - class CrudCreateView(CrudMixin, crud_create_mixin, CreateView): + class CrudCreateView(CrudMixin, create_mixin, CreateView): pass - class CrudDetailView(CrudMixin, crud_detail_mixin, DetailView): + class CrudDetailView(CrudMixin, detail_mixin, DetailView): pass - class CrudUpdateView(CrudMixin, crud_update_mixin, UpdateView): + class CrudUpdateView(CrudMixin, update_mixin, UpdateView): pass - class CrudDeleteView(CrudMixin, crud_delete_mixin, DeleteView): + class CrudDeleteView(CrudMixin, delete_mixin, DeleteView): pass self.urlpatterns = [ diff --git a/crud_tests/views.py b/crud_tests/views.py index 9255c1938..60aad8743 100644 --- a/crud_tests/views.py +++ b/crud_tests/views.py @@ -15,4 +15,4 @@ country_crud = Crud( ], ['More Details', [('description', 12)]], ], - crud_list_mixin=CountryCrudListMixin) + list_mixin=CountryCrudListMixin)