django-importexport-flow 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- django_importexport_flow/__init__.py +81 -0
- django_importexport_flow/admin/__init__.py +23 -0
- django_importexport_flow/admin/export_definition.py +90 -0
- django_importexport_flow/admin/export_request.py +47 -0
- django_importexport_flow/admin/generate_export.py +133 -0
- django_importexport_flow/admin/import_config.py +57 -0
- django_importexport_flow/admin/import_data.py +158 -0
- django_importexport_flow/admin/import_definition.py +154 -0
- django_importexport_flow/admin/import_request.py +72 -0
- django_importexport_flow/apps.py +8 -0
- django_importexport_flow/engine/__init__.py +12 -0
- django_importexport_flow/engine/core.py +106 -0
- django_importexport_flow/engine/pdf.py +20 -0
- django_importexport_flow/engine/table.py +233 -0
- django_importexport_flow/forms.py +184 -0
- django_importexport_flow/managers.py +16 -0
- django_importexport_flow/migrations/0001_initial.py +148 -0
- django_importexport_flow/migrations/__init__.py +0 -0
- django_importexport_flow/models/__init__.py +15 -0
- django_importexport_flow/models/config_pdf.py +37 -0
- django_importexport_flow/models/config_table.py +62 -0
- django_importexport_flow/models/export_definition.py +121 -0
- django_importexport_flow/models/export_request.py +85 -0
- django_importexport_flow/models/import_definition.py +160 -0
- django_importexport_flow/models/import_request.py +94 -0
- django_importexport_flow/utils/__init__.py +6 -0
- django_importexport_flow/utils/export.py +154 -0
- django_importexport_flow/utils/filter_form.py +103 -0
- django_importexport_flow/utils/helpers.py +355 -0
- django_importexport_flow/utils/http.py +21 -0
- django_importexport_flow/utils/import_tabular.py +1199 -0
- django_importexport_flow/utils/serialization.py +361 -0
- django_importexport_flow/utils/validation.py +313 -0
- django_importexport_flow-0.1.0.dist-info/METADATA +80 -0
- django_importexport_flow-0.1.0.dist-info/RECORD +38 -0
- django_importexport_flow-0.1.0.dist-info/WHEEL +5 -0
- django_importexport_flow-0.1.0.dist-info/licenses/LICENSE +22 -0
- django_importexport_flow-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""django-importexport-flow package."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("django-importexport-flow")
|
|
7
|
+
except PackageNotFoundError:
|
|
8
|
+
__version__ = "0.0.0"
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"ExportConfigPdf",
|
|
12
|
+
"ExportConfigTable",
|
|
13
|
+
"ExportDefinition",
|
|
14
|
+
"ImportDefinition",
|
|
15
|
+
"ImportRequest",
|
|
16
|
+
"ExportRequest",
|
|
17
|
+
"ExportManager",
|
|
18
|
+
"__version__",
|
|
19
|
+
"get_export_definitions",
|
|
20
|
+
"serialize_export_configuration",
|
|
21
|
+
"serialize_import_definition",
|
|
22
|
+
"import_import_definition",
|
|
23
|
+
"serialize_report_import",
|
|
24
|
+
"import_report_import",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def __getattr__(name: str):
|
|
29
|
+
if name == "ExportManager":
|
|
30
|
+
from .managers import ExportManager
|
|
31
|
+
|
|
32
|
+
return ExportManager
|
|
33
|
+
if name == "serialize_export_configuration":
|
|
34
|
+
from .utils.serialization import serialize_export_configuration
|
|
35
|
+
|
|
36
|
+
return serialize_export_configuration
|
|
37
|
+
if name == "serialize_import_definition":
|
|
38
|
+
from .utils.serialization import serialize_import_definition
|
|
39
|
+
|
|
40
|
+
return serialize_import_definition
|
|
41
|
+
if name == "import_import_definition":
|
|
42
|
+
from .utils.serialization import import_import_definition
|
|
43
|
+
|
|
44
|
+
return import_import_definition
|
|
45
|
+
if name == "serialize_report_import":
|
|
46
|
+
from .utils.serialization import serialize_report_import
|
|
47
|
+
|
|
48
|
+
return serialize_report_import
|
|
49
|
+
if name == "import_report_import":
|
|
50
|
+
from .utils.serialization import import_report_import
|
|
51
|
+
|
|
52
|
+
return import_report_import
|
|
53
|
+
if name == "get_export_definitions":
|
|
54
|
+
from .utils import get_export_definitions
|
|
55
|
+
|
|
56
|
+
return get_export_definitions
|
|
57
|
+
if name == "ExportDefinition":
|
|
58
|
+
from .models import ExportDefinition
|
|
59
|
+
|
|
60
|
+
return ExportDefinition
|
|
61
|
+
if name == "ExportConfigPdf":
|
|
62
|
+
from .models import ExportConfigPdf
|
|
63
|
+
|
|
64
|
+
return ExportConfigPdf
|
|
65
|
+
if name == "ExportConfigTable":
|
|
66
|
+
from .models import ExportConfigTable
|
|
67
|
+
|
|
68
|
+
return ExportConfigTable
|
|
69
|
+
if name == "ImportDefinition":
|
|
70
|
+
from .models import ImportDefinition
|
|
71
|
+
|
|
72
|
+
return ImportDefinition
|
|
73
|
+
if name == "ImportRequest":
|
|
74
|
+
from .models import ImportRequest
|
|
75
|
+
|
|
76
|
+
return ImportRequest
|
|
77
|
+
if name == "ExportRequest":
|
|
78
|
+
from .models import ExportRequest
|
|
79
|
+
|
|
80
|
+
return ExportRequest
|
|
81
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Django admin registration for django-importexport-flow."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
# Load modules so @admin.register runs.
|
|
6
|
+
from . import export_definition # noqa: F401
|
|
7
|
+
from . import import_definition # noqa: F401
|
|
8
|
+
from . import import_request # noqa: F401
|
|
9
|
+
from . import export_request # noqa: F401
|
|
10
|
+
|
|
11
|
+
from .export_definition import (
|
|
12
|
+
ExportConfigPdfInline,
|
|
13
|
+
ExportConfigTableInline,
|
|
14
|
+
ExportDefinitionAdmin,
|
|
15
|
+
)
|
|
16
|
+
from .import_definition import ImportDefinitionAdmin
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"ExportConfigPdfInline",
|
|
20
|
+
"ExportConfigTableInline",
|
|
21
|
+
"ExportDefinitionAdmin",
|
|
22
|
+
"ImportDefinitionAdmin",
|
|
23
|
+
]
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from django.contrib import admin
|
|
4
|
+
from django.contrib import messages
|
|
5
|
+
from django.core.exceptions import PermissionDenied
|
|
6
|
+
from django.urls import reverse
|
|
7
|
+
from django.utils.translation import gettext_lazy as _
|
|
8
|
+
|
|
9
|
+
from django_boosted import AdminBoostModel, admin_boost_view
|
|
10
|
+
|
|
11
|
+
from ..forms import ExportConfigurationImportForm
|
|
12
|
+
from ..models import ExportConfigPdf, ExportConfigTable, ExportDefinition
|
|
13
|
+
from ..utils.serialization import import_export_configuration, serialize_export_configuration
|
|
14
|
+
from .generate_export import GenerateExportMixin
|
|
15
|
+
from .import_config import run_json_configuration_import
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ExportConfigPdfInline(admin.StackedInline):
|
|
19
|
+
model = ExportConfigPdf
|
|
20
|
+
extra = 0
|
|
21
|
+
classes = ("collapse",)
|
|
22
|
+
fields = ("template", "configuration")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ExportConfigTableInline(admin.StackedInline):
|
|
26
|
+
model = ExportConfigTable
|
|
27
|
+
extra = 0
|
|
28
|
+
classes = ("collapse",)
|
|
29
|
+
fields = ("columns", "configuration")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@admin.register(ExportDefinition)
|
|
33
|
+
class ExportDefinitionAdmin(GenerateExportMixin, AdminBoostModel):
|
|
34
|
+
list_display = ("name", "target", "manager", "uuid")
|
|
35
|
+
search_fields = ("name", "description", "uuid")
|
|
36
|
+
readonly_fields = (
|
|
37
|
+
"uuid",
|
|
38
|
+
"created_by",
|
|
39
|
+
"updated_by",
|
|
40
|
+
"created_at",
|
|
41
|
+
"updated_at",
|
|
42
|
+
)
|
|
43
|
+
inlines = (ExportConfigPdfInline, ExportConfigTableInline)
|
|
44
|
+
fieldsets = (
|
|
45
|
+
(None, {"fields": ("name", "uuid", "description")}),
|
|
46
|
+
(
|
|
47
|
+
_("Model and queryset"),
|
|
48
|
+
{"fields": ("target", "manager", "order_by")},
|
|
49
|
+
),
|
|
50
|
+
(
|
|
51
|
+
_("Filters"),
|
|
52
|
+
{"fields": ("filter_config", "filter_request", "filter_mandatory")},
|
|
53
|
+
),
|
|
54
|
+
(
|
|
55
|
+
_("Audit"),
|
|
56
|
+
{"fields": ("created_by", "updated_by", "created_at", "updated_at")},
|
|
57
|
+
),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
@admin_boost_view("json", _("Export configuration (JSON)"))
|
|
61
|
+
def export_configuration_json(self, request, obj):
|
|
62
|
+
return serialize_export_configuration(obj)
|
|
63
|
+
|
|
64
|
+
@admin_boost_view("adminform", _("Import configuration (JSON)"))
|
|
65
|
+
def import_configuration_json(self, request, form=None):
|
|
66
|
+
if not self.has_add_permission(request) and not self.has_change_permission(
|
|
67
|
+
request
|
|
68
|
+
):
|
|
69
|
+
raise PermissionDenied
|
|
70
|
+
if form is None:
|
|
71
|
+
return {"form": ExportConfigurationImportForm()}
|
|
72
|
+
imported = run_json_configuration_import(
|
|
73
|
+
request,
|
|
74
|
+
form,
|
|
75
|
+
import_export_configuration,
|
|
76
|
+
log_label="import_export_configuration",
|
|
77
|
+
)
|
|
78
|
+
if imported is None:
|
|
79
|
+
return {"form": form}
|
|
80
|
+
messages.success(
|
|
81
|
+
request,
|
|
82
|
+
_("Imported export “%(name)s”.") % {"name": imported.name},
|
|
83
|
+
)
|
|
84
|
+
opts = self.model._meta
|
|
85
|
+
url = reverse(
|
|
86
|
+
f"admin:{opts.app_label}_{opts.model_name}_change",
|
|
87
|
+
args=[imported.pk],
|
|
88
|
+
current_app=self.admin_site.name,
|
|
89
|
+
)
|
|
90
|
+
return {"redirect_url": url}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Admin for :class:`~django_importexport_flow.models.ExportRequest` (export audit)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from django.contrib import admin
|
|
6
|
+
from django.utils.translation import gettext_lazy as _
|
|
7
|
+
|
|
8
|
+
from ..models import ExportRequest
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@admin.register(ExportRequest)
|
|
12
|
+
class ExportRequestAdmin(admin.ModelAdmin):
|
|
13
|
+
list_display = (
|
|
14
|
+
"uuid",
|
|
15
|
+
"export_definition",
|
|
16
|
+
"export_format",
|
|
17
|
+
"status",
|
|
18
|
+
"output_bytes",
|
|
19
|
+
"created_at",
|
|
20
|
+
"completed_at",
|
|
21
|
+
"initiated_by",
|
|
22
|
+
"created_by",
|
|
23
|
+
"updated_by",
|
|
24
|
+
"updated_at",
|
|
25
|
+
)
|
|
26
|
+
list_filter = ("status", "export_format", "created_at")
|
|
27
|
+
search_fields = ("uuid",)
|
|
28
|
+
readonly_fields = (
|
|
29
|
+
"uuid",
|
|
30
|
+
"export_definition",
|
|
31
|
+
"export_format",
|
|
32
|
+
"filter_payload",
|
|
33
|
+
"status",
|
|
34
|
+
"output_bytes",
|
|
35
|
+
"error_trace",
|
|
36
|
+
"created_at",
|
|
37
|
+
"completed_at",
|
|
38
|
+
"initiated_by",
|
|
39
|
+
"created_by",
|
|
40
|
+
"updated_by",
|
|
41
|
+
"updated_at",
|
|
42
|
+
)
|
|
43
|
+
ordering = ("-created_at",)
|
|
44
|
+
|
|
45
|
+
def has_add_permission(self, request):
|
|
46
|
+
"""Rows are created by *Generate export* only."""
|
|
47
|
+
return False
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Admin mixin: generate table export with filter_request (GET) + filter_config merge."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import re
|
|
8
|
+
import traceback
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from django.contrib import messages
|
|
12
|
+
from django.core.exceptions import PermissionDenied, ValidationError
|
|
13
|
+
from django.http import HttpResponse
|
|
14
|
+
from django.utils import timezone
|
|
15
|
+
from django.utils.translation import gettext_lazy as _
|
|
16
|
+
|
|
17
|
+
from django_boosted import admin_boost_view
|
|
18
|
+
from django_boosted.decorators import AdminBoostViewConfig
|
|
19
|
+
|
|
20
|
+
from ..utils.export import definition_has_table_config, run_table_export
|
|
21
|
+
from ..forms import make_export_form_class
|
|
22
|
+
from ..models import ExportRequest
|
|
23
|
+
from ..utils.http import content_disposition_attachment
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def safe_download_stem(
|
|
29
|
+
raw_name: str | None,
|
|
30
|
+
*,
|
|
31
|
+
fallback: str = "export",
|
|
32
|
+
max_len: int = 80,
|
|
33
|
+
) -> str:
|
|
34
|
+
"""Sanitize a title or name for use as a download filename stem (no extension)."""
|
|
35
|
+
base = re.sub(r"[^\w\-.]+", "_", raw_name or "").strip("_") or fallback
|
|
36
|
+
return base[:max_len]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _safe_export_filename(name: str) -> str:
|
|
40
|
+
return safe_download_stem(name, fallback="export")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _export_timestamp_for_filename() -> str:
|
|
44
|
+
"""Local time, second precision, safe for filenames (e.g. ``20260329_143045``)."""
|
|
45
|
+
return timezone.localtime(timezone.now()).strftime("%Y%m%d_%H%M%S")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _filter_payload_snapshot(cleaned_data: dict[str, Any]) -> dict[str, Any]:
|
|
49
|
+
"""JSON-safe subset: ``export_format`` and ``fr_*`` keys only."""
|
|
50
|
+
subset = {
|
|
51
|
+
k: v
|
|
52
|
+
for k, v in cleaned_data.items()
|
|
53
|
+
if k == "export_format" or k.startswith("fr_")
|
|
54
|
+
}
|
|
55
|
+
return json.loads(json.dumps(subset, default=str))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def dated_export_filename(safe_stem: str, ext: str) -> str:
|
|
59
|
+
"""
|
|
60
|
+
``safe_stem`` = basename without extension (already sanitized).
|
|
61
|
+
``ext`` must include the leading dot (e.g. ``.csv``).
|
|
62
|
+
"""
|
|
63
|
+
return f"{safe_stem}_{_export_timestamp_for_filename()}{ext}"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class GenerateExportMixin:
|
|
67
|
+
@admin_boost_view(
|
|
68
|
+
"adminform",
|
|
69
|
+
_("Generate export"),
|
|
70
|
+
config=AdminBoostViewConfig(permission="change"),
|
|
71
|
+
)
|
|
72
|
+
def generate_export(self, request, obj, form=None):
|
|
73
|
+
if not self.has_change_permission(request, obj):
|
|
74
|
+
raise PermissionDenied
|
|
75
|
+
FormClass = make_export_form_class(obj)
|
|
76
|
+
if form is None:
|
|
77
|
+
return {"form": FormClass()}
|
|
78
|
+
if not form.is_valid():
|
|
79
|
+
return {"form": form}
|
|
80
|
+
if not definition_has_table_config(obj):
|
|
81
|
+
messages.error(
|
|
82
|
+
request,
|
|
83
|
+
_("Add a table configuration (columns) before exporting."),
|
|
84
|
+
)
|
|
85
|
+
return {"form": form}
|
|
86
|
+
cleaned = form.cleaned_data
|
|
87
|
+
payload = _filter_payload_snapshot(cleaned)
|
|
88
|
+
export_fmt = str(cleaned.get("export_format") or "")
|
|
89
|
+
user = (
|
|
90
|
+
request.user
|
|
91
|
+
if getattr(request.user, "is_authenticated", False)
|
|
92
|
+
else None
|
|
93
|
+
)
|
|
94
|
+
try:
|
|
95
|
+
content, content_type, ext = run_table_export(obj, cleaned)
|
|
96
|
+
except (ValidationError, ValueError) as exc:
|
|
97
|
+
ExportRequest.objects.create(
|
|
98
|
+
export_definition=obj,
|
|
99
|
+
export_format=export_fmt,
|
|
100
|
+
filter_payload=payload,
|
|
101
|
+
status=ExportRequest.Status.FAILURE,
|
|
102
|
+
error_trace=str(exc),
|
|
103
|
+
completed_at=timezone.now(),
|
|
104
|
+
initiated_by=user,
|
|
105
|
+
)
|
|
106
|
+
messages.error(request, str(exc))
|
|
107
|
+
return {"form": form}
|
|
108
|
+
except Exception:
|
|
109
|
+
logger.exception("Table export failed for export definition %r", getattr(obj, "pk", None))
|
|
110
|
+
ExportRequest.objects.create(
|
|
111
|
+
export_definition=obj,
|
|
112
|
+
export_format=export_fmt,
|
|
113
|
+
filter_payload=payload,
|
|
114
|
+
status=ExportRequest.Status.FAILURE,
|
|
115
|
+
error_trace=traceback.format_exc(),
|
|
116
|
+
completed_at=timezone.now(),
|
|
117
|
+
initiated_by=user,
|
|
118
|
+
)
|
|
119
|
+
messages.error(request, _("Export failed."))
|
|
120
|
+
return {"form": form}
|
|
121
|
+
ExportRequest.objects.create(
|
|
122
|
+
export_definition=obj,
|
|
123
|
+
export_format=export_fmt,
|
|
124
|
+
filter_payload=payload,
|
|
125
|
+
status=ExportRequest.Status.SUCCESS,
|
|
126
|
+
output_bytes=len(content),
|
|
127
|
+
completed_at=timezone.now(),
|
|
128
|
+
initiated_by=user,
|
|
129
|
+
)
|
|
130
|
+
filename = dated_export_filename(_safe_export_filename(obj.name), ext)
|
|
131
|
+
response = HttpResponse(content, content_type=content_type)
|
|
132
|
+
response["Content-Disposition"] = content_disposition_attachment(filename)
|
|
133
|
+
return response
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Shared admin logic for JSON report configuration import."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from django.contrib import messages
|
|
10
|
+
from django.core.exceptions import ValidationError
|
|
11
|
+
from django.core.serializers.base import DeserializationError
|
|
12
|
+
from django.db import IntegrityError
|
|
13
|
+
from django.http import HttpRequest
|
|
14
|
+
from django.utils.translation import gettext_lazy as _
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def run_json_configuration_import(
|
|
20
|
+
request: HttpRequest,
|
|
21
|
+
form: Any,
|
|
22
|
+
import_fn: Callable[[dict[str, Any]], Any],
|
|
23
|
+
*,
|
|
24
|
+
log_label: str,
|
|
25
|
+
) -> Any | None:
|
|
26
|
+
"""
|
|
27
|
+
Call ``import_fn(form.import_data)`` and surface errors via messages.
|
|
28
|
+
|
|
29
|
+
Returns the imported instance on success, or ``None`` on failure (the view
|
|
30
|
+
should then return ``{"form": form}``).
|
|
31
|
+
"""
|
|
32
|
+
try:
|
|
33
|
+
return import_fn(form.import_data)
|
|
34
|
+
except (ValueError, ValidationError) as exc:
|
|
35
|
+
messages.error(request, str(exc))
|
|
36
|
+
return None
|
|
37
|
+
except DeserializationError as exc:
|
|
38
|
+
logger.warning("%s JSON deserialize failed: %s", log_label, exc)
|
|
39
|
+
messages.error(
|
|
40
|
+
request,
|
|
41
|
+
_("Could not read the configuration from this file."),
|
|
42
|
+
)
|
|
43
|
+
return None
|
|
44
|
+
except IntegrityError as exc:
|
|
45
|
+
logger.warning("%s import integrity error: %s", log_label, exc)
|
|
46
|
+
messages.error(
|
|
47
|
+
request,
|
|
48
|
+
_("Import failed: this configuration conflicts with existing data."),
|
|
49
|
+
)
|
|
50
|
+
return None
|
|
51
|
+
except Exception:
|
|
52
|
+
logger.exception("%s failed", log_label)
|
|
53
|
+
messages.error(
|
|
54
|
+
request,
|
|
55
|
+
_("Import failed. Check the file format and try again."),
|
|
56
|
+
)
|
|
57
|
+
return None
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Admin wizard: upload → preview table → confirm import."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from django.contrib import messages
|
|
9
|
+
from django.core.exceptions import PermissionDenied
|
|
10
|
+
from django.http import HttpResponse
|
|
11
|
+
from django.shortcuts import render
|
|
12
|
+
from django.utils.translation import gettext_lazy as _
|
|
13
|
+
|
|
14
|
+
from django_boosted import admin_boost_view
|
|
15
|
+
from django_boosted.decorators import AdminBoostViewConfig
|
|
16
|
+
|
|
17
|
+
from ..forms import (
|
|
18
|
+
MAX_TABULAR_IMPORT_BYTES,
|
|
19
|
+
TabularImportForm,
|
|
20
|
+
make_tabular_import_form_class,
|
|
21
|
+
)
|
|
22
|
+
from ..utils.import_tabular import (
|
|
23
|
+
create_import_request,
|
|
24
|
+
read_uploaded_tabular,
|
|
25
|
+
run_tabular_import_for_request,
|
|
26
|
+
validate_import_preview,
|
|
27
|
+
)
|
|
28
|
+
from ..utils import dataframe_preview_table
|
|
29
|
+
from ..models import ImportRequest
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
# ``admin/change_form.html`` only sets ``enctype="multipart/form-data"`` when
|
|
34
|
+
# ``has_file_field`` is true; otherwise POST drops uploaded files.
|
|
35
|
+
_UPLOAD_FORM_CONTEXT = {"import_preview": False, "has_file_field": True}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _filter_keys_from_cleaned(cleaned: dict) -> dict:
|
|
39
|
+
return {k: v for k, v in cleaned.items() if k.startswith("fr_")}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ImportDataPreviewMixin:
|
|
43
|
+
@admin_boost_view(
|
|
44
|
+
"adminform",
|
|
45
|
+
_("Import data (preview)"),
|
|
46
|
+
config=AdminBoostViewConfig(
|
|
47
|
+
permission="change",
|
|
48
|
+
template_name="django_importexport_flow/admin/report_import_import_data.html",
|
|
49
|
+
),
|
|
50
|
+
)
|
|
51
|
+
def import_tabular_data(self, request, obj, form=None):
|
|
52
|
+
if not self.has_change_permission(request, obj):
|
|
53
|
+
raise PermissionDenied
|
|
54
|
+
FormClass = make_tabular_import_form_class(obj)
|
|
55
|
+
|
|
56
|
+
if form is None:
|
|
57
|
+
return {
|
|
58
|
+
"form": FormClass(initial={"step": TabularImportForm.STEP_UPLOAD}),
|
|
59
|
+
**_UPLOAD_FORM_CONTEXT,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if not form.is_valid():
|
|
63
|
+
return {"form": form, **_UPLOAD_FORM_CONTEXT}
|
|
64
|
+
|
|
65
|
+
cleaned = form.cleaned_data
|
|
66
|
+
step = cleaned.get("step") or TabularImportForm.STEP_UPLOAD
|
|
67
|
+
|
|
68
|
+
if step == TabularImportForm.STEP_UPLOAD:
|
|
69
|
+
upload = cleaned["file"]
|
|
70
|
+
try:
|
|
71
|
+
df = read_uploaded_tabular(upload, MAX_TABULAR_IMPORT_BYTES)
|
|
72
|
+
except Exception as exc:
|
|
73
|
+
messages.error(request, str(exc))
|
|
74
|
+
return {"form": form, **_UPLOAD_FORM_CONTEXT}
|
|
75
|
+
|
|
76
|
+
errs, warns, resolved_cols, df_norm = validate_import_preview(df, obj)
|
|
77
|
+
for w in warns:
|
|
78
|
+
messages.warning(request, w)
|
|
79
|
+
if errs:
|
|
80
|
+
for e in errs:
|
|
81
|
+
messages.error(request, e)
|
|
82
|
+
return {"form": form, **_UPLOAD_FORM_CONTEXT}
|
|
83
|
+
|
|
84
|
+
filter_subset = _filter_keys_from_cleaned(cleaned)
|
|
85
|
+
ask_kw: dict[str, Any] = {"inferred_column_paths": resolved_cols}
|
|
86
|
+
try:
|
|
87
|
+
ask = create_import_request(
|
|
88
|
+
obj,
|
|
89
|
+
upload,
|
|
90
|
+
filter_subset,
|
|
91
|
+
request.user,
|
|
92
|
+
**ask_kw,
|
|
93
|
+
)
|
|
94
|
+
except Exception as exc:
|
|
95
|
+
logger.exception("Creating ImportRequest failed")
|
|
96
|
+
messages.error(request, str(exc))
|
|
97
|
+
return {"form": form, **_UPLOAD_FORM_CONTEXT}
|
|
98
|
+
|
|
99
|
+
preview_columns, preview_rows = dataframe_preview_table(
|
|
100
|
+
df_norm if df_norm is not None else df,
|
|
101
|
+
limit=30,
|
|
102
|
+
)
|
|
103
|
+
context = {
|
|
104
|
+
**self.admin_site.each_context(request),
|
|
105
|
+
"title": _("Confirm import"),
|
|
106
|
+
"opts": self.model._meta,
|
|
107
|
+
"original": obj,
|
|
108
|
+
"preview_rows": preview_rows,
|
|
109
|
+
"preview_columns": preview_columns,
|
|
110
|
+
"import_request_uuid": str(ask.uuid),
|
|
111
|
+
}
|
|
112
|
+
return render(
|
|
113
|
+
request,
|
|
114
|
+
"django_importexport_flow/admin/report_import_import_confirm.html",
|
|
115
|
+
context,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
uid = cleaned.get("import_request_uuid")
|
|
119
|
+
ask = (
|
|
120
|
+
ImportRequest.objects.filter(
|
|
121
|
+
uuid=uid,
|
|
122
|
+
import_definition=obj,
|
|
123
|
+
status=ImportRequest.Status.PENDING,
|
|
124
|
+
)
|
|
125
|
+
.first()
|
|
126
|
+
)
|
|
127
|
+
if ask is None:
|
|
128
|
+
messages.error(request, _("Import request not found or already processed."))
|
|
129
|
+
return {
|
|
130
|
+
"form": FormClass(initial={"step": TabularImportForm.STEP_UPLOAD}),
|
|
131
|
+
**_UPLOAD_FORM_CONTEXT,
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
run_tabular_import_for_request(ask)
|
|
135
|
+
ask.refresh_from_db()
|
|
136
|
+
|
|
137
|
+
if ask.status == ImportRequest.Status.SUCCESS:
|
|
138
|
+
messages.success(
|
|
139
|
+
request,
|
|
140
|
+
_("Imported %(n)s row(s).") % {"n": ask.imported_row_count or 0},
|
|
141
|
+
)
|
|
142
|
+
else:
|
|
143
|
+
messages.error(
|
|
144
|
+
request,
|
|
145
|
+
_("Import failed. See the import request record for details."),
|
|
146
|
+
)
|
|
147
|
+
if ask.error_trace:
|
|
148
|
+
messages.error(request, ask.error_trace[:4000])
|
|
149
|
+
|
|
150
|
+
opts = self.model._meta
|
|
151
|
+
from django.urls import reverse
|
|
152
|
+
|
|
153
|
+
url = reverse(
|
|
154
|
+
f"admin:{opts.app_label}_{opts.model_name}_change",
|
|
155
|
+
args=[obj.pk],
|
|
156
|
+
current_app=self.admin_site.name,
|
|
157
|
+
)
|
|
158
|
+
return {"redirect_url": url}
|