Browse Source

Atualiza requirements e ajusta sistema para nova versão do django-import-export

pull/163/head
Sesostris Vieira 2 years ago
parent
commit
bfcc3e7d90
  1. 2
      requirements/dev-requirements.txt
  2. 10
      requirements/requirements.txt
  3. 21
      sigi/apps/casas/admin.py
  4. 6
      sigi/apps/parlamentares/admin.py
  5. 88
      sigi/apps/utils/mixins.py
  6. 12
      sigi/apps/utils/static/js/exportformfields.js
  7. 1
      sigi/apps/utils/templates/admin/import_export/export.html

2
requirements/dev-requirements.txt

@ -1,4 +1,4 @@
-r requirements.txt -r requirements.txt
black==22.12.0 black==23.1.0
ipdb==0.13.11 ipdb==0.13.11
pygraphviz==1.10 pygraphviz==1.10

10
requirements/requirements.txt

@ -2,21 +2,21 @@ dnspython==2.3.0
docutils==0.19 docutils==0.19
gunicorn==20.1.0 gunicorn==20.1.0
ibge==0.0.5 ibge==0.0.5
ipython==8.10.0 ipython==8.11.0
pandas==1.5.3 pandas==1.5.3
Pillow==9.4.0 Pillow==9.4.0
psycopg2-binary==2.9.5 psycopg2-binary==2.9.5
python-docx==0.8.11 python-docx==0.8.11
requests==2.28.2 requests==2.28.2
weasyprint==57.2 weasyprint==58.0
XlsxWriter==3.0.7 XlsxWriter==3.0.8
Django==4.1.7 Django==4.1.7
django-auth-ldap==4.1.0 django-auth-ldap==4.1.0
django_debug_toolbar==3.8.1 django_debug_toolbar==3.8.1
django-environ==0.9.0 django-environ==0.10.0
django-extensions==3.2.1 django-extensions==3.2.1
django-filter==22.1 django-filter==22.1
django-import-export==2.9.0 django-import-export==3.1.0
django-localflavor==3.1 django-localflavor==3.1
django-material-admin==1.8.6 django-material-admin==1.8.6
django-tinymce==3.5.0 django-tinymce==3.5.0

21
sigi/apps/casas/admin.py

@ -30,7 +30,23 @@ from sigi.apps.utils.mixins import (
) )
class OrgaoExportResourse(LabeledResourse): class OrgaoExportResourceContato(LabeledResourse):
class Meta:
model = Orgao
fields = ("nome", "email")
export_order = fields
name = "Exportação para aplicativo Contatos"
def dehydrate_nome(self, orgao):
return orgao.nome[:50]
def export(self, queryset=None, *args, **kwargs):
if queryset is not None:
queryset = queryset.exclude(email="")
return super().export(queryset, *args, **kwargs)
class OrgaoExportResourseGeral(LabeledResourse):
presidente = Field(column_name="presidente") presidente = Field(column_name="presidente")
telefone = Field(column_name="telefone") telefone = Field(column_name="telefone")
# servicos_seit = Field(column_name='servicos_seit') # servicos_seit = Field(column_name='servicos_seit')
@ -57,6 +73,7 @@ class OrgaoExportResourse(LabeledResourse):
"contato", "contato",
) )
export_order = fields export_order = fields
name = "Exportação de uso geral"
def dehydrate_nome(self, orgao): def dehydrate_nome(self, orgao):
return orgao.nome[:50] return orgao.nome[:50]
@ -292,7 +309,7 @@ class FuncionarioAdmin(ReturnMixin, admin.ModelAdmin):
@admin.register(Orgao) @admin.register(Orgao)
class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin): class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin):
form = OrgaoForm form = OrgaoForm
resource_class = OrgaoExportResourse resource_classes = [OrgaoExportResourseGeral, OrgaoExportResourceContato]
inlines = ( inlines = (
TelefonesInline, TelefonesInline,
ParlamentarInline, ParlamentarInline,

6
sigi/apps/parlamentares/admin.py

@ -18,7 +18,7 @@ from sigi.apps.parlamentares.forms import ImportForm
from sigi.apps.utils.filters import AlphabeticFilter from sigi.apps.utils.filters import AlphabeticFilter
from sigi.apps.utils.mixins import ( from sigi.apps.utils.mixins import (
ReturnMixin, ReturnMixin,
ImportCartExportMixin, CartImportExportMixin,
CartExportMixin, CartExportMixin,
LabeledResourse, LabeledResourse,
) )
@ -140,7 +140,7 @@ class ParlamentarNomeCompletoFilter(AlphabeticFilter):
@admin.register(Partido) @admin.register(Partido)
class PartidoAdmin(ImportCartExportMixin, admin.ModelAdmin): class PartidoAdmin(CartImportExportMixin, admin.ModelAdmin):
list_display = ("legenda", "nome", "sigla") list_display = ("legenda", "nome", "sigla")
search_fields = ("legenda", "nome", "sigla") search_fields = ("legenda", "nome", "sigla")
@ -148,7 +148,7 @@ class PartidoAdmin(ImportCartExportMixin, admin.ModelAdmin):
@admin.register(Parlamentar) @admin.register(Parlamentar)
class ParlamentarAdmin(ReturnMixin, CartExportMixin, admin.ModelAdmin): class ParlamentarAdmin(ReturnMixin, CartExportMixin, admin.ModelAdmin):
resource_class = ParlamentarResource resource_class = ParlamentarResource
change_list_template = ( import_export_change_list_template = (
"admin/parlamentares/parlamentar/cart/" "admin/parlamentares/parlamentar/cart/"
"change_list_import_cart_export.html" "change_list_import_cart_export.html"
) )

88
sigi/apps/utils/mixins.py

@ -38,15 +38,23 @@ class ValueField(Field):
class ExportFormFields(ExportForm): class ExportFormFields(ExportForm):
def __init__(self, formats, field_list, *args, **kwargs): def __init__(self, formats, resource_classes, *args, **kwargs):
super().__init__(formats, *args, **kwargs) super().__init__(formats, resource_classes, *args, **kwargs)
self.fields["selected_fields"] = forms.MultipleChoiceField( for i, resource_klass in enumerate(resource_classes):
label=_("Campos a exportar"), resource = resource_klass()
required=True, field_list = list(
choices=field_list, zip(resource.get_export_order(), resource.get_export_headers())
initial=[f[0] for f in field_list], )
widget=forms.CheckboxSelectMultiple, self.fields[f"selected_fields_{i}"] = forms.MultipleChoiceField(
) label=_("Campos a exportar"),
required=False,
choices=field_list,
initial=[f[0] for f in field_list],
widget=forms.CheckboxSelectMultiple,
)
class Media:
js = ("js/exportformfields.js",)
class LabeledResourse(resources.ModelResource): class LabeledResourse(resources.ModelResource):
@ -87,17 +95,20 @@ class ValueLabeledResource(LabeledResourse):
class CartExportMixin(ExportMixin): class CartExportMixin(ExportMixin):
to_encoding = "utf-8" to_encoding = "utf-8"
change_list_template = "admin/cart/change_list_cart_export.html" import_export_change_list_template = (
"admin/cart/change_list_cart_export.html"
)
export_form_class = ExportFormFields
_cart_session_name = None _cart_session_name = None
_cart_viewing_name = None _cart_viewing_name = None
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(CartExportMixin, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self._cart_session_name = "cart_%s" % self.opts.model_name self._cart_session_name = "cart_%s" % self.opts.model_name
self._cart_viewing_name = "view_cart_%s" % self.opts.model_name self._cart_viewing_name = "view_cart_%s" % self.opts.model_name
def get_queryset(self, request): def get_queryset(self, request):
qs = super(CartExportMixin, self).get_queryset(request) qs = super().get_queryset(request)
if self._cart_viewing_name in request.session: if self._cart_viewing_name in request.session:
ids = request.session.get(self._cart_session_name, []) ids = request.session.get(self._cart_session_name, [])
qs = qs.filter(id__in=ids) qs = qs.filter(id__in=ids)
@ -113,7 +124,7 @@ class CartExportMixin(ExportMixin):
else: else:
self.actions = list(self.actions) self.actions = list(self.actions)
self.actions.append("add_to_cart") self.actions.append("add_to_cart")
return super(CartExportMixin, self).get_actions(request) return super().get_actions(request)
@csrf_protect_m @csrf_protect_m
def changelist_view(self, request, extra_context=None): def changelist_view(self, request, extra_context=None):
@ -147,6 +158,13 @@ class CartExportMixin(ExportMixin):
] ]
return my_urls + urls return my_urls + urls
def get_data_for_export(self, request, queryset, *args, **kwargs):
export_form = kwargs.get("export_form", None)
resource_index = self.get_resource_index(export_form)
field_name = f"selected_fields_{resource_index}"
kwargs["selected_fields"] = export_form.cleaned_data[field_name]
return super().get_data_for_export(request, queryset, *args, **kwargs)
@csrf_protect_m @csrf_protect_m
def add_to_cart(self, request, queryset): def add_to_cart(self, request, queryset):
if request.POST.get("select_across", "0") == "0": if request.POST.get("select_across", "0") == "0":
@ -212,52 +230,16 @@ class CartExportMixin(ExportMixin):
self.message_user(request, _("Carrinho vazio")) self.message_user(request, _("Carrinho vazio"))
return HttpResponseRedirect("..") return HttpResponseRedirect("..")
@csrf_protect_m
def export_action(self, request, *args, **kwargs):
if not self.has_export_permission(request):
raise PermissionDenied
formats = self.get_export_formats()
resource = (self.get_export_resource_class())()
field_list = list(
zip(resource.get_export_order(), resource.get_export_headers())
)
form = ExportFormFields(formats, field_list, request.POST or None)
if form.is_valid():
file_format = formats[int(form.cleaned_data["file_format"])]()
queryset = self.get_export_queryset(request)
export_data = self.get_export_data(
file_format,
queryset,
request=request,
encoding=self.to_encoding,
selected_fields=form.cleaned_data["selected_fields"],
)
content_type = file_format.get_content_type()
response = HttpResponse(export_data, content_type=content_type)
response["Content-Disposition"] = 'attachment; filename="%s"' % (
self.get_export_filename(request, queryset, file_format),
)
post_export.send(sender=None, model=self.model)
return response
context = self.get_export_context_data() class CartImportExportMixin(ImportMixin, CartExportMixin):
context["title"] = _("Export")
context["form"] = form
context["opts"] = self.model._meta
request.current_app = self.admin_site.name
return TemplateResponse(request, [self.export_template_name], context)
class ImportCartExportMixin(ImportMixin, CartExportMixin):
""" """
Import and export mixin. Import and export mixin.
""" """
#: template for change_list view #: template for change_list view
change_list_template = "admin/cart/change_list_import_cart_export.html" import_export_change_list_template = (
"admin/cart/change_list_import_cart_export.html"
)
class CartExportReportMixin(CartExportMixin): class CartExportReportMixin(CartExportMixin):

12
sigi/apps/utils/static/js/exportformfields.js

@ -0,0 +1,12 @@
$(document).ready(function () {
if ($("#id_resource").length) {
$("#id_resource").change(change_resource);
change_resource();
}
});
function change_resource() {
var selected_resource_id = $("#id_resource").val();
$("div[id^=id_selected_fields").parent().hide();
$(`div#id_selected_fields_${selected_resource_id}`).parent().show();
}

1
sigi/apps/utils/templates/admin/import_export/export.html

@ -3,6 +3,7 @@
{% block extrastyle %} {% block extrastyle %}
{{ block.super }} {{ block.super }}
{{ form.media }}
<style> <style>
#content { #content {
display: block; display: block;

Loading…
Cancel
Save