diff --git a/sapl/api/deprecated.py b/sapl/api/deprecated.py index 45f5a12ae..db27f2ac1 100644 --- a/sapl/api/deprecated.py +++ b/sapl/api/deprecated.py @@ -207,13 +207,15 @@ class AutoresPossiveisFilterSet(FilterSet): if legislatura_relativa.atual(): q = q & Q(parlamentar_set__ativo=True) - legislatura_anterior = self.request.GET.get('legislatura_anterior', 'False') + legislatura_anterior = self.request.GET.get( + 'legislatura_anterior', 'False') if legislatura_anterior.lower() == 'true': legislaturas = Legislatura.objects.filter( data_fim__lte=data_relativa).order_by('-data_fim')[:2] if len(legislaturas) == 2: _, leg_anterior = legislaturas - q = q | Q(parlamentar_set__mandato__data_inicio_mandato__gte=leg_anterior.data_inicio) + q = q | Q( + parlamentar_set__mandato__data_inicio_mandato__gte=leg_anterior.data_inicio) qs = queryset.filter(q) return qs @@ -390,33 +392,6 @@ class SessaoPlenariaOldSerializer(serializers.ModelSerializer): return casa -class ModelChoiceView(ListAPIView): - """ - Deprecated - - TODO Migrar para customização na api automática - - """ - - # FIXME aplicar permissão correta de usuário - permission_classes = (IsAuthenticated,) - serializer_class = ModelChoiceSerializer - - def get(self, request, *args, **kwargs): - self.model = ContentType.objects.get_for_id( - self.kwargs['content_type']).model_class() - - pagination = request.GET.get('pagination', '') - - if pagination == 'False': - self.pagination_class = None - - return ListAPIView.get(self, request, *args, **kwargs) - - def get_queryset(self): - return self.model.objects.all() - - class AutorListView(ListAPIView): """ Deprecated diff --git a/sapl/api/urls.py b/sapl/api/urls.py index ddfa93df4..7a48e0fb4 100644 --- a/sapl/api/urls.py +++ b/sapl/api/urls.py @@ -6,8 +6,7 @@ from rest_framework.authtoken.views import obtain_auth_token from rest_framework.routers import DefaultRouter from sapl.api.deprecated import MateriaLegislativaViewSet, SessaoPlenariaViewSet, \ - AutoresProvaveisListView, AutoresPossiveisListView, AutorListView, \ - ModelChoiceView + AutoresProvaveisListView, AutoresPossiveisListView, AutorListView from sapl.api.views import AppVersionView, recria_token from sapl.api.viewset import SaplApiViewSetConstrutor @@ -44,8 +43,7 @@ deprecated_urlpatterns_api = [ url(r'^autor/possiveis', AutoresPossiveisListView.as_view(), name='autores_possiveis_list'), url(r'^autor', AutorListView.as_view(), name='autor_list'), - url(r'^model/(?P\d+)/(?P\d*)$', - ModelChoiceView.as_view(), name='model_list'), + ] urlpatterns = [ diff --git a/sapl/materia/forms.py b/sapl/materia/forms.py index 06bb15f7a..1af4b7aa9 100644 --- a/sapl/materia/forms.py +++ b/sapl/materia/forms.py @@ -1490,10 +1490,20 @@ class TramitacaoEmLoteFilterSet(django_filters.FilterSet): class TipoProposicaoForm(ModelForm): + content_types_choices = [ + ( + f'{ct.app_label}/{ct.model}', + ct + ) + for k, ct in ContentType.objects.get_for_models( + *models_with_gr_for_model(TipoProposicao) + ).items() + ] + logger = logging.getLogger(__name__) - content_type = forms.ModelChoiceField( - queryset=ContentType.objects.all(), + content_type = forms.ChoiceField( + choices=content_types_choices, label=TipoProposicao._meta.get_field('content_type').verbose_name, required=True, help_text=TipoProposicao._meta.get_field('content_type').help_text) @@ -1550,18 +1560,6 @@ class TipoProposicaoForm(ModelForm): super(TipoProposicaoForm, self).__init__(*args, **kwargs) - content_types = ContentType.objects.get_for_models( - *models_with_gr_for_model(TipoProposicao)) - - self.fields['content_type'].choices = [ - (ct.pk, ct) for k, ct in content_types.items()] - # Ordena por id - self.fields['content_type'].choices.sort(key=lambda x: x[0]) - - if self.instance.pk: - self.fields[ - 'tipo_conteudo_related'].initial = self.instance.object_id - def clean(self): super(TipoProposicaoForm, self).clean() @@ -1570,7 +1568,16 @@ class TipoProposicaoForm(ModelForm): cd = self.cleaned_data - content_type = cd['content_type'] + content_type = cd['content_type'].split('/') + content_type = ContentType.objects.filter( + app_label=content_type[0], + model=content_type[1]).first() + cd['content_type'] = content_type + + if not content_type: + self.logger.error("Meta Tipo Inexistente") + raise ValidationError( + _('Meta Tipo Inexistente.')) if 'tipo_conteudo_related' not in cd or not cd[ 'tipo_conteudo_related']: diff --git a/sapl/materia/views.py b/sapl/materia/views.py index d02959e83..78066464f 100644 --- a/sapl/materia/views.py +++ b/sapl/materia/views.py @@ -477,6 +477,13 @@ class TipoProposicaoCrud(CrudAux): form_class = TipoProposicaoForm layout_key = None + def get_initial(self): + initial = CrudAux.UpdateView.get_initial(self) + ct = self.object.content_type + initial['content_type'] = f'{ct.app_label}/{ct.model}' + initial['tipo_conteudo_related'] = self.object.object_id + return initial + def criar_materia_proposicao(proposicao): tipo_materia = TipoMateriaLegislativa.objects.get( diff --git a/sapl/templates/materia/tipoproposicao_form.html b/sapl/templates/materia/tipoproposicao_form.html index 7d412a3c2..1ea6e8879 100644 --- a/sapl/templates/materia/tipoproposicao_form.html +++ b/sapl/templates/materia/tipoproposicao_form.html @@ -20,40 +20,49 @@ $(document).ready(function(){ var initial_select = parseInt($("input[name=tipo_conteudo_related]").val()); $("input[name=tipo_conteudo_related]").remove(); $('#id_content_type').change(function(event) { - var pk = this[event.target.selectedIndex].value; - var url = '{% url 'sapl.api:model_list' 0 ''%}' - url = url.replace('0', pk) + '?pagination=False' - - $.get(url).done(function(data) { - if (data === undefined || data.length == 0) { - $( "#dialog" ).dialog({ - resizable: false, - height: "auto", - width: 400, - modal: true, - buttons: { - OK: function() { - $( this ).dialog( "close" ); - } - } - }); - return; - } - - var radios = $("#div_id_tipo_conteudo_related_radio > div").html(''); - data.forEach(function (val, index) { - var html_radio = '
'; - - if (val.value === initial_select) - initial_select=0; - radios.append(html_radio); - }); - }); - }); - $('#id_content_type').trigger('change'); -}); - + const url_part_pattern = this[event.target.selectedIndex].value + const url = `/api/${url_part_pattern}/?o=id&page=1&page_size=100` + const rad_tip_conteudo = $("#div_id_tipo_conteudo_related_radio > div").html(''); + const popule_rad_tip_conteudo = function(url_get) { + $.get(url_get).done(function(response) { + if (response.pagination.total_entries === 0) { + $( "#dialog" ).dialog({ + resizable: false, + height: "auto", + width: 400, + modal: true, + buttons: { + OK: function() { + $( this ).dialog( "close" ); + } + } + }); + return; + } + response.results.forEach(function (val, index) { + var html_radio = ` +
+ +
` + if (val.id === initial_select) + initial_select=0; + rad_tip_conteudo.append(html_radio); + }) + if(response.pagination.links.next !== null ) + popule_rad_tip_conteudo(response.pagination.links.next) + }) + } + popule_rad_tip_conteudo(url) + }) + $('#id_content_type').trigger('change') +}) - {% endblock %}