From 72e04fe0862ffb09878e3ba9e35f2f4b24f79c16 Mon Sep 17 00:00:00 2001 From: Louis Date: Mon, 26 Oct 2026 21:26:52 +0100 Subject: [PATCH] feat(i18n): translate UI and import messages to English with German catalogue English is now the source language for the dashboard, forms, menu, JavaScript progress texts and all import/export messages; a complete German catalogue ships as package data. Tenant-error detection also accepts the error code and the active-language message of netbox_utilities, and no longer imports netbox_utilities when it is installed but not enabled. A test keeps the README NetBox range in sync with min_version/max_version. Co-Authored-By: Claude Opus 5.5 --- README.md | 15 + netbox_export/forms.py | 51 ++- netbox_export/locale/de/LC_MESSAGES/django.mo | Bin 0 -> 12360 bytes netbox_export/locale/de/LC_MESSAGES/django.po | 428 ++++++++++++++++++ netbox_export/navigation.py | 3 +- netbox_export/services/archive.py | 41 +- netbox_export/services/graph.py | 7 +- netbox_export/services/importer.py | 105 +++-- netbox_export/services/plugin_compat.py | 48 +- netbox_export/services/references.py | 16 +- .../templates/netbox_export/dashboard.html | 47 +- netbox_export/views.py | 10 + pyproject.toml | 6 +- tests/test_archive.py | 14 +- tests/test_cable_import.py | 2 +- tests/test_device_placement.py | 6 +- tests/test_file_import.py | 4 +- tests/test_importer_plugin_compat.py | 10 +- tests/test_metadata.py | 38 ++ tests/test_plugin_compat.py | 8 +- tests/test_references.py | 10 +- 21 files changed, 713 insertions(+), 156 deletions(-) create mode 100644 netbox_export/locale/de/LC_MESSAGES/django.mo create mode 100644 netbox_export/locale/de/LC_MESSAGES/django.po create mode 100644 tests/test_metadata.py diff --git a/README.md b/README.md index 820c4b5..50ca692 100644 --- a/README.md +++ b/README.md @@ -219,12 +219,27 @@ conflict strategy **Abort import** still aborts on existing objects. - Encrypted credentials of NetBox-VM-Import are only usable with an identical Django `SECRET_KEY`; otherwise set the password again on the target. +### Language + +The plugin is available in English (source) and German. Switch the display +language as usual in the user profile (**Preferences → Language**); import +reports and error messages follow it. Translations live in +`netbox_export/locale/de/LC_MESSAGES/`. + ## Development and tests ```bash python -m pytest ``` +After changing user-visible strings, update and compile the German catalogue: + +```bash +cd netbox_export +django-admin makemessages -l de --no-location +msgfmt -o locale/de/LC_MESSAGES/django.mo locale/de/LC_MESSAGES/django.po +``` + ## License Apache License 2.0 — see [LICENSE](LICENSE). diff --git a/netbox_export/forms.py b/netbox_export/forms.py index 7a89d6d..e34a727 100644 --- a/netbox_export/forms.py +++ b/netbox_export/forms.py @@ -1,26 +1,27 @@ from dcim.models import Location, Region, Site from django import forms +from django.utils.translation import gettext_lazy as _ from tenancy.models import Tenant, TenantGroup class ExportForm(forms.Form): scope_type = forms.ChoiceField( - label="Exportbereich", + label=_("Export scope"), choices=( - ("tenant_group", "Mandantengruppe"), - ("tenant", "Mandant"), - ("region", "Region"), - ("site", "Standort"), - ("location", "Lokation"), + ("tenant_group", _("Tenant group")), + ("tenant", _("Tenant")), + ("region", _("Region")), + ("site", _("Site")), + ("location", _("Location")), ), ) tenant_group = forms.ModelChoiceField( - label="Mandantengruppe", queryset=TenantGroup.objects.all(), required=False + label=_("Tenant group"), queryset=TenantGroup.objects.all(), required=False ) - tenant = forms.ModelChoiceField(label="Mandant", queryset=Tenant.objects.all(), required=False) - region = forms.ModelChoiceField(label="Region", queryset=Region.objects.all(), required=False) - site = forms.ModelChoiceField(label="Standort", queryset=Site.objects.all(), required=False) - location = forms.ModelChoiceField(label="Lokation", queryset=Location.objects.all(), required=False) + tenant = forms.ModelChoiceField(label=_("Tenant"), queryset=Tenant.objects.all(), required=False) + region = forms.ModelChoiceField(label=_("Region"), queryset=Region.objects.all(), required=False) + site = forms.ModelChoiceField(label=_("Site"), queryset=Site.objects.all(), required=False) + location = forms.ModelChoiceField(label=_("Location"), queryset=Location.objects.all(), required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -32,47 +33,47 @@ class ExportForm(forms.Form): scope_type = cleaned.get("scope_type") selected = cleaned.get(scope_type) if scope_type else None if scope_type and selected is None: - self.add_error(scope_type, "Bitte ein Objekt für den Exportbereich auswählen.") + self.add_error(scope_type, _("Select an object for the export scope.")) cleaned["scope_object"] = selected return cleaned class ImportForm(forms.Form): archive = forms.FileField( - label="NetBox-Export-Archiv", + label=_("NetBox-Export archive"), widget=forms.ClearableFileInput(attrs={"accept": ".zip,application/zip"}), ) conflict_strategy = forms.ChoiceField( - label="Vorhandene Objekte", + label=_("Existing objects"), choices=( - ("update", "Aktualisieren"), - ("skip", "Überspringen"), - ("fail", "Import abbrechen"), + ("update", _("Update")), + ("skip", _("Skip")), + ("fail", _("Abort import")), ), initial="update", ) dry_run = forms.BooleanField( - label="Nur prüfen (keine Änderungen)", + label=_("Check only (no changes)"), required=False, initial=True, - help_text="Führt den vollständigen Import aus und setzt die Datenbanktransaktion anschließend zurück.", + help_text=_("Runs the complete import and then rolls back the database transaction."), ) force = forms.BooleanField( - label="Force-Modus (Fehler überspringen)", + label=_("Force mode (skip errors)"), required=False, initial=False, - help_text=( - "Objekte, deren Import fehlschlägt, werden einzeln übersprungen, statt den gesamten Import " - "zurückzurollen. Übersprungene Objekte werden im Bericht als Warnung aufgeführt." + help_text=_( + "Objects that fail to import are skipped individually instead of rolling back the whole import. " + "Skipped objects are listed as warnings in the report." ), ) confirm_apply = forms.BooleanField( - label="Ich bestätige den schreibenden Import", + label=_("I confirm the writing import"), required=False, ) def clean(self): cleaned = super().clean() if not cleaned.get("dry_run") and not cleaned.get("confirm_apply"): - self.add_error("confirm_apply", "Für einen schreibenden Import ist die Bestätigung erforderlich.") + self.add_error("confirm_apply", _("Confirmation is required for a writing import.")) return cleaned diff --git a/netbox_export/locale/de/LC_MESSAGES/django.mo b/netbox_export/locale/de/LC_MESSAGES/django.mo new file mode 100644 index 0000000000000000000000000000000000000000..211d6009d243802a354b19f0f7e5348102b89f9f GIT binary patch literal 12360 zcmbW7ZH!#idB<-OQosg9*m^H>;1EHkJotZN;m%VfE zaPJ+jy-Lz5tyEIcmncQ~P$WLYtx#waP$VQIs~@_lDz*JUzqM+WqO_k{wW_M1s%fkA z_dn;{nLC3Qn~pg9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I?=r^8y;ySPSXI!G{X^GIr zKlsVDg+$5IRi4CKyfbt>3ae~vT~LOsiXjP;GNjs{x$I){%f*w(`w*R_P5>I!N1t$5 zs*gvf{ITZAIv#CfGzzvdK4o*wpgVo$gYP;8%cL(3`*;DBRtR^_qhBPaQdsguNbko= zUxd_vrAU+MriNeg1u34AB*@=!W0`tZ{j*qCg~)(5>lf7bY$PiRE)fqp*t(Eb$lIJ{ zUhA_~3Gp3!1^LYM@>FzLyBx0^x%`$YlHOWZV~Ub7iSpKKD7iV73}UFFq-?57O%d(l z@?B}sIdq@#QEK5~wRMqj(Hu>DlJ65o#@XhWpr{Kv`P=bniL%7`yOU;Ii!q*=@fz)y z(8bDeB1?$3@0r`h*}V6wu#b#|!Tu~;3J37}kLhvaoGcOZ$1Rm8046c1x=P2?cn;AP;4 z#A#MXjv+~<%%L+jikhSkWLaEn{c_AR!pGw=ybO~}(>e*la7yu8FM6rD%bEKpO!A{- zIIIcaQV=^d9LZHTy@Q2X48v?(qJ0UXmoCECkXUgQBojl>(`v0tx0{pro6@A*>E8!; zK4U{yJ~fgFX}S;L!H1Fwkls~t4fVZ6N8uhuM$E%HofTDFSYaOdm~9hNFF~)mINOW| z>6Ob6!uo-#J|u4+mvHH)z@e+P=d=^Hmp@~j(+(SJ9k-c_#LgHzGcG~*E9JOciwZa{ zRs~+dH>GIXkX?z;Mq=?+{C_6O5JlQ)RlqAje7*D*ng*tP`beQ-%+Nb+k$yw9kLmyv zr#wsL#Cw%)Jcjcz|A?&rdr8ThKYHJ)bmJm~+`=I540ugy!T}uHofWt=E;t)JBqf7z z&mpc*K5*+ekrSG^k-MVI5pGm=Otod2BtRQiW5R^}G3&^eyTCM)_%}1&E~eE;;3h#m zvtxH-@_D7oq;0z%yG!Enkc5XCYC_a$k*D_zoatCh6${iRT z_ str: normalized = posixpath.normpath(name.replace("\\", "/")) if normalized.startswith(("../", "/")) or normalized in ("", ".", ".."): - raise ArchiveValidationError(f"Unsicherer Dateipfad im Archiv: {name}") + raise ArchiveValidationError(_("Unsafe file path in archive: %(path)s") % {"path": name}) return normalized @@ -118,52 +119,52 @@ def read_archive( else: raw = source.read(max_size + 1) if len(raw) > max_size: - raise ArchiveValidationError("Das Archiv überschreitet die konfigurierte Maximalgröße.") + raise ArchiveValidationError(_("The archive exceeds the configured maximum size.")) try: archive = zipfile.ZipFile(io.BytesIO(raw)) except zipfile.BadZipFile as exc: - raise ArchiveValidationError("Die hochgeladene Datei ist kein gültiges ZIP-Archiv.") from exc + raise ArchiveValidationError(_("The uploaded file is not a valid ZIP archive.")) from exc with archive: names = {} for info in archive.infolist(): name = _safe_member_name(info.filename) if name in names: - raise ArchiveValidationError(f"Doppelter Dateipfad im Archiv: {name}") + raise ArchiveValidationError(_("Duplicate file path in archive: %(path)s") % {"path": name}) names[name] = info if len(names) > max_objects * 5 + 2: - raise ArchiveValidationError("Das Archiv enthält zu viele Dateien.") + raise ArchiveValidationError(_("The archive contains too many files.")) if MANIFEST_NAME not in names or OBJECTS_NAME not in names: - raise ArchiveValidationError("manifest.json oder objects.ndjson fehlt im Archiv.") + raise ArchiveValidationError(_("manifest.json or objects.ndjson is missing from the archive.")) total_size = sum(info.file_size for info in names.values()) if total_size > max_size * 4: - raise ArchiveValidationError("Der entpackte Archivinhalt ist zu groß.") + raise ArchiveValidationError(_("The extracted archive content is too large.")) if any(info.file_size > 0 and info.compress_size * 200 < info.file_size for info in names.values()): - raise ArchiveValidationError("Das Archiv weist ein unzulässiges Kompressionsverhältnis auf.") + raise ArchiveValidationError(_("The archive has an impermissible compression ratio.")) try: manifest = json.loads(archive.read(MANIFEST_NAME)) object_data = archive.read(OBJECTS_NAME) except (KeyError, ValueError, UnicodeDecodeError) as exc: - raise ArchiveValidationError("Die Metadaten im Archiv sind ungültig.") from exc + raise ArchiveValidationError(_("The archive metadata is invalid.")) from exc if manifest.get("format") != FORMAT_NAME or manifest.get("format_version") != FORMAT_VERSION: - raise ArchiveValidationError("Das Archivformat oder dessen Version wird nicht unterstützt.") + raise ArchiveValidationError(_("The archive format or its version is not supported.")) checksum = hashlib.sha256(object_data).hexdigest() if not hmac.compare_digest(checksum, str(manifest.get("objects_sha256", ""))): - raise ArchiveValidationError("Die Objektdatei stimmt nicht mit ihrer Prüfsumme überein.") + raise ArchiveValidationError(_("The object file does not match its checksum.")) warnings = [] signature = manifest.get("signature") if signing_key: expected = _signature(manifest, signing_key) if not signature or not hmac.compare_digest(expected, signature): - raise ArchiveValidationError("Die Archivsignatur ist ungültig oder fehlt.") + raise ArchiveValidationError(_("The archive signature is invalid or missing.")) elif signature: - warnings.append("Das Archiv ist signiert, aber ohne konfigurierten Schlüssel nicht verifiziert.") + warnings.append(_("The archive is signed but was not verified because no key is configured.")) else: - warnings.append("Das Archiv ist nicht signiert.") + warnings.append(_("The archive is not signed.")) records = [] try: @@ -171,9 +172,9 @@ def read_archive( if line: records.append(json.loads(line)) if len(records) > max_objects: - raise ArchiveValidationError("Das Archiv enthält zu viele Objekte.") + raise ArchiveValidationError(_("The archive contains too many objects.")) except (ValueError, UnicodeDecodeError) as exc: - raise ArchiveValidationError("objects.ndjson enthält ungültiges JSON.") from exc + raise ArchiveValidationError(_("objects.ndjson contains invalid JSON.")) from exc assets = { name: archive.read(name) @@ -182,11 +183,11 @@ def read_archive( } declared_assets = manifest.get("assets_sha256", {}) if set(declared_assets) != set(assets): - raise ArchiveValidationError("Die Dateiliste stimmt nicht mit dem Manifest überein.") + raise ArchiveValidationError(_("The file list does not match the manifest.")) for name, content in assets.items(): actual = hashlib.sha256(content).hexdigest() if not hmac.compare_digest(actual, str(declared_assets.get(name, ""))): - raise ArchiveValidationError(f"Die Prüfsumme der Datei {name} ist ungültig.") + raise ArchiveValidationError(_("The checksum of file %(name)s is invalid.") % {"name": name}) if manifest.get("object_count") != len(records): - raise ArchiveValidationError("Die Objektanzahl stimmt nicht mit dem Manifest überein.") + raise ArchiveValidationError(_("The object count does not match the manifest.")) return ParsedArchive(manifest=manifest, records=records, assets=assets, warnings=warnings) diff --git a/netbox_export/services/graph.py b/netbox_export/services/graph.py index d1e6a1f..24ed01e 100644 --- a/netbox_export/services/graph.py +++ b/netbox_export/services/graph.py @@ -6,6 +6,7 @@ from django.apps import apps from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models +from django.utils.translation import gettext as _ from .codec import object_key from .exceptions import GraphLimitError @@ -153,8 +154,10 @@ class ObjectGraph: object_count = len(self.members) + len(self.dependencies) if object_count > self.max_objects: raise GraphLimitError( - f"Der Export würde mehr als {self.max_objects} Objekte enthalten. " - "Bitte den Bereich verkleinern oder max_objects erhöhen." + _( + "The export would contain more than %(max)s objects. " + "Narrow the scope or increase max_objects." + ) % {"max": self.max_objects} ) def add_member(self, obj) -> bool: diff --git a/netbox_export/services/importer.py b/netbox_export/services/importer.py index 60bcaea..7a4f74b 100644 --- a/netbox_export/services/importer.py +++ b/netbox_export/services/importer.py @@ -18,6 +18,7 @@ from django.contrib.contenttypes.models import ContentType from django.core.files.base import ContentFile from django.db import IntegrityError, models, transaction from django.db.models import Value +from django.utils.translation import gettext as _ from PIL import Image as PillowImage from netbox_export.models import ImportedObjectMapping @@ -105,9 +106,9 @@ def _model_for(label: str): try: model = apps.get_model(label) except (LookupError, ValueError) as exc: - raise ArchiveValidationError(f"Das Modell {label} ist auf der Zielinstanz nicht installiert.") from exc + raise ArchiveValidationError(_("The model %(model)s is not installed on the target instance.") % {"model": label}) from exc if model is None: - raise ArchiveValidationError(f"Das Modell {label} ist auf der Zielinstanz nicht installiert.") + raise ArchiveValidationError(_("The model %(model)s is not installed on the target instance.") % {"model": label}) return model @@ -313,8 +314,11 @@ def _find_existing(source_instance, model, record, resolver): if mapped is not None and mapped.pk != natural.pk: resolver.warn( ("mapping-rebound", record["id"]), - f"Gespeicherte Zuordnung für {record['id']} wurde von Ziel-ID {mapped.pk} auf " - f"Ziel-ID {natural.pk} korrigiert, da der Fachschlüssel {dict(lookup)} bereits existiert.", + _( + "Stored mapping for %(record)s was corrected from target ID %(old)s to target ID %(new)s " + "because the natural key %(key)s already exists." + ) + % {"record": record["id"], "old": mapped.pk, "new": natural.pk, "key": dict(lookup)}, ) return natural @@ -418,7 +422,7 @@ def _apply_device_placements( for record_id, placement in placements: rack, available = resolver.resolve(placement.rack_spec) if not available: - raise ArchiveValidationError(f"Rack-Referenz für {record_id} konnte nicht aufgelöst werden.") + raise ArchiveValidationError(_("Rack reference for %(record)s could not be resolved.") % {"record": record_id}) if rack is MISSING_REFERENCE: continue @@ -428,7 +432,7 @@ def _apply_device_placements( if rack is None and (position is not None or face is not None): resolver.warn( ("device-placement-without-rack", record_id), - f"Rackplatz für {record_id} wurde ausgelassen, da kein Rack zugeordnet ist.", + _("Rack position for %(record)s was omitted because no rack is assigned.") % {"record": record_id}, ) position = None face = None @@ -445,14 +449,18 @@ def _apply_device_placements( occupants = _conflicting_devices(conflicts) if conflict_strategy == "fail": raise ImportConflictError( - f"Rackplatzkonflikt für {record_id}: {target} ist durch Zielgerät(e) {occupants} belegt." + _("Rack position conflict for %(record)s: %(target)s is occupied by target device(s) %(occupants)s.") + % {"record": record_id, "target": target, "occupants": occupants} ) if conflict_strategy == "skip": _save_device_placement(device, rack, None, None, compatibility) resolver.warn( ("device-placement-skipped", record_id), - f"Rackplatz für {record_id} wurde übersprungen: {target} bleibt durch " - f"Zielgerät(e) {occupants} belegt. Das importierte Gerät wurde ohne Position im Rack gespeichert.", + _( + "Rack position for %(record)s was skipped: %(target)s remains occupied by target device(s) " + "%(occupants)s. The imported device was saved without a rack position." + ) + % {"record": record_id, "target": target, "occupants": occupants}, ) continue @@ -463,8 +471,11 @@ def _apply_device_placements( _save_device_placement(device, rack, position, face, compatibility) resolver.warn( ("device-placement-released", record_id), - f"Rackplatzkonflikt für {record_id} gelöst: Zielgerät(e) {occupants} wurden aus {target} " - "gelöst und ohne Position im Rack belassen.", + _( + "Rack position conflict for %(record)s resolved: target device(s) %(occupants)s were removed " + "from %(target)s and left without a rack position." + ) + % {"record": record_id, "occupants": occupants, "target": target}, ) @@ -503,8 +514,10 @@ def _release_port_mapping_conflicts(obj, resolver, record_id): conflict.delete() resolver.warn( ("port-mapping-replaced", record_id), - f"Portzuordnung(en) {conflict_ids} wurden durch {record_id} ersetzt, damit die " - "Front-/Rear-Port-Verkabelung der Quelle entspricht.", + _( + "Port mapping(s) %(ids)s were replaced by %(record)s so the front/rear port cabling matches the source." + ) + % {"ids": conflict_ids, "record": record_id}, ) @@ -640,8 +653,8 @@ def _open_image_with_bounded_override(data): except PillowImage.DecompressionBombError as exc: stream.close() raise ArchiveValidationError( - "Das Bild überschreitet die sichere Importgrenze von " - f"{IMPORTED_IMAGE_SOURCE_MAX_PIXELS:,} Pixeln." + _("The image exceeds the safe import limit of %(max)s pixels.") + % {"max": f"{IMPORTED_IMAGE_SOURCE_MAX_PIXELS:,}"} ) from exc except Exception: stream.close() @@ -673,8 +686,8 @@ def _prepare_image_asset(data): source_pixels = width * height if source_pixels > IMPORTED_IMAGE_SOURCE_MAX_PIXELS: raise ArchiveValidationError( - f"Das Bild mit {source_pixels:,} Pixeln überschreitet die sichere Importgrenze von " - f"{IMPORTED_IMAGE_SOURCE_MAX_PIXELS:,} Pixeln." + _("The image with %(pixels)s pixels exceeds the safe import limit of %(max)s pixels.") + % {"pixels": f"{source_pixels:,}", "max": f"{IMPORTED_IMAGE_SOURCE_MAX_PIXELS:,}"} ) if source_pixels <= NETBOX_IMAGE_MAX_PIXELS: return data, width, height, None @@ -714,8 +727,8 @@ def _set_files(obj, record, assets, saved_files, *, dry_run: bool, import_warnin old_width, old_height, new_width, new_height = resize_info record_id = record.get("id", obj._meta.label_lower) import_warnings.append( - f"Bild für {record_id} wurde von {old_width}×{old_height} auf " - f"{new_width}×{new_height} Pixel verkleinert." + _("Image for %(record)s was downscaled from %(old)s to %(new)s pixels.") + % {"record": record_id, "old": f"{old_width}×{old_height}", "new": f"{new_width}×{new_height}"} ) if dry_run: continue @@ -748,7 +761,7 @@ def _apply_m2m(obj, record, resolver): for spec in specs: value, available = resolver.resolve(spec) if not available: - raise ArchiveValidationError(f"M2M-Referenz für {record['id']} konnte nicht aufgelöst werden.") + raise ArchiveValidationError(_("M2M reference for %(record)s could not be resolved.") % {"record": record["id"]}) if value is MISSING_REFERENCE: continue values.append(value) @@ -781,7 +794,7 @@ def _forced(force, warnings, label, func, *args, **kwargs): except ImportConflictError: raise except Exception as exc: # noqa: BLE001 - force mode skips any failing step - warnings.append(f"Force-Modus: {label} wurde wegen eines Fehlers übersprungen: {exc}") + warnings.append(_("Force mode: %(label)s was skipped because of an error: %(error)s") % {"label": label, "error": exc}) return None @@ -801,8 +814,11 @@ def _skip_uninstalled_optional_models(records, resolver, report): del records[record_id] for label in sorted(missing_labels): report.warnings.append( - f"Objekte vom Typ {label} wurden übersprungen, da das zugehörige optionale Plugin " - "auf der Zielinstanz nicht installiert ist." + _( + "Objects of type %(model)s were skipped because the related optional plugin is not installed " + "on the target instance." + ) + % {"model": label} ) @@ -810,24 +826,25 @@ def import_archive( parsed: ParsedArchive, *, conflict_strategy: str, dry_run: bool, force: bool = False ) -> ImportReport: if conflict_strategy not in ("update", "skip", "fail"): - raise ArchiveValidationError("Unbekannte Konfliktstrategie.") + raise ArchiveValidationError(_("Unknown conflict strategy.")) source_version = str(parsed.manifest.get("source_netbox_version", "")) target_version = str(getattr(getattr(settings, "RELEASE", None), "version", "")) if source_version and target_version and source_version.split(".")[:2] != target_version.split(".")[:2]: raise ArchiveValidationError( - f"NetBox-Versionen sind nicht kompatibel: Quelle {source_version}, Ziel {target_version}." + _("NetBox versions are not compatible: source %(source)s, target %(target)s.") + % {"source": source_version, "target": target_version} ) try: source_instance = uuid.UUID(parsed.manifest["source_instance"]) except (KeyError, TypeError, ValueError) as exc: - raise ArchiveValidationError("Die Quellinstanz-Kennung fehlt oder ist ungültig.") from exc + raise ArchiveValidationError(_("The source instance ID is missing or invalid.")) from exc records = {} for record in parsed.records: if not all(key in record for key in ("id", "model", "source_pk")): - raise ArchiveValidationError("Ein Objektdatensatz ist unvollständig.") + raise ArchiveValidationError(_("An object record is incomplete.")) if record["id"] in records: - raise ArchiveValidationError(f"Doppelte Objekt-ID im Archiv: {record['id']}") + raise ArchiveValidationError(_("Duplicate object ID in archive: %(record)s") % {"record": record["id"]}) records[record["id"]] = record report = ImportReport(dry_run=dry_run, warnings=list(parsed.warnings)) @@ -867,7 +884,7 @@ def import_archive( except IdentityNotReady: continue if existing is not None and conflict_strategy == "fail": - raise ImportConflictError(f"Zielobjekt existiert bereits: {record_id}") + raise ImportConflictError(_("Target object already exists: %(record)s") % {"record": record_id}) if existing is not None and conflict_strategy == "skip": obj = existing @@ -905,7 +922,7 @@ def import_archive( raise resolver.skipped.add(record_id) report.warnings.append( - f"Force-Modus: {record_id} wurde wegen eines Fehlers übersprungen: {exc}" + _("Force mode: %(label)s was skipped because of an error: %(error)s") % {"label": record_id, "error": exc} ) report.add(record["model"], "skipped") pending.pop(record_id) @@ -934,12 +951,12 @@ def import_archive( resolver.skipped.add(record_id) report.add(record["model"], "skipped") report.warnings.append( - f"Force-Modus: {len(pending)} Objekt(e) mit nicht auflösbaren Referenzen " - f"wurden übersprungen: {blocked}" + _("Force mode: %(count)s object(s) with unresolvable references were skipped: %(blocked)s") + % {"count": len(pending), "blocked": blocked} ) break raise ArchiveValidationError( - f"Erforderliche Referenzen konnten nicht aufgelöst werden: {blocked}" + _("Required references could not be resolved: %(blocked)s") % {"blocked": blocked} ) for record_id, name, spec in deferred_relations: @@ -947,13 +964,13 @@ def import_archive( continue value, available = resolver.resolve(spec) if not available: - raise ArchiveValidationError(f"Referenz {name} für {record_id} konnte nicht aufgelöst werden.") + raise ArchiveValidationError(_("Reference %(name)s for %(record)s could not be resolved.") % {"name": name, "record": record_id}) if value is MISSING_REFERENCE: continue _forced( force, report.warnings, - f"Referenz {name} für {record_id}", + _("Reference %(name)s for %(record)s") % {"name": name, "record": record_id}, _apply_deferred_relation, resolved[record_id], name, @@ -966,7 +983,7 @@ def import_archive( continue value, available = resolver.resolve(spec) if not available: - raise ArchiveValidationError(f"Generische Referenz {name} für {record_id} fehlt.") + raise ArchiveValidationError(_("Generic reference %(name)s for %(record)s is missing.") % {"name": name, "record": record_id}) if value is MISSING_REFERENCE: continue obj = resolved[record_id] @@ -975,7 +992,7 @@ def import_archive( _forced( force, report.warnings, - f"Generische Referenz {name} für {record_id}", + _("Generic reference %(name)s for %(record)s") % {"name": name, "record": record_id}, compatibility.save, obj, update_fields=[field.ct_field, field.fk_field], @@ -986,13 +1003,13 @@ def import_archive( continue value, available = _decode_archived_value(encoded, resolver) if not available: - raise ArchiveValidationError(f"Custom-Field-Referenz {name} für {record_id} fehlt.") + raise ArchiveValidationError(_("Custom field reference %(name)s for %(record)s is missing.") % {"name": name, "record": record_id}) obj = resolved[record_id] setattr(obj, name, value) _forced( force, report.warnings, - f"Custom-Field-Wert {name} für {record_id}", + _("Custom field value %(name)s for %(record)s") % {"name": name, "record": record_id}, compatibility.save, obj, update_fields=[name], @@ -1001,7 +1018,7 @@ def import_archive( _forced( force, report.warnings, - "Rackplatzierung der Geräte", + _("Rack placement of devices"), _apply_device_placements, deferred_device_placements, resolved, @@ -1015,7 +1032,7 @@ def import_archive( _forced( force, report.warnings, - f"Mehrfachzuordnungen für {record_id}", + _("Many-to-many assignments for %(record)s") % {"record": record_id}, _apply_m2m, resolved[record_id], record, @@ -1025,7 +1042,7 @@ def import_archive( _forced( force, report.warnings, - "Neuberechnung der Kabelpfade", + _("Recalculation of cable paths"), _rebuild_imported_cable_paths, records, resolved, @@ -1035,11 +1052,11 @@ def import_archive( transaction.set_rollback(True) except (IntegrityError, ValueError, TypeError) as exc: _cleanup_files(saved_files) - raise ArchiveValidationError(f"Der Import wurde zurückgerollt: {exc}") from exc + raise ArchiveValidationError(_("The import was rolled back: %(error)s") % {"error": exc}) from exc except ExportImportError: _cleanup_files(saved_files) raise except Exception as exc: _cleanup_files(saved_files) - raise ArchiveValidationError(f"Der Import wurde zurückgerollt: {exc}") from exc + raise ArchiveValidationError(_("The import was rolled back: %(error)s") % {"error": exc}) from exc return report diff --git a/netbox_export/services/plugin_compat.py b/netbox_export/services/plugin_compat.py index 03a1d4e..834fa8a 100644 --- a/netbox_export/services/plugin_compat.py +++ b/netbox_export/services/plugin_compat.py @@ -5,10 +5,12 @@ from functools import cache from django.apps import apps from django.core.exceptions import FieldDoesNotExist, ValidationError from django.db import models +from django.utils.translation import gettext as _ AUTO_IMPORT_TENANT_NAME = "Auto-Import" AUTO_IMPORT_TENANT_SLUG = "auto-import" -MISSING_TENANT_MESSAGE = "Für dieses Objekt muss ein Mandant angegeben werden." +MISSING_TENANT_MESSAGE = "Für dieses Objekt muss ein Mandant angegeben werden." # netbox_utilities before i18n +MISSING_TENANT_CODE = "tenant_required" # Apps of optional plugins whose data is exported when installed on the source # and skipped (instead of failing the import) when missing on the target. OPTIONAL_PLUGIN_APP_LABELS = frozenset({"netbox_utilities"}) @@ -20,6 +22,8 @@ def is_optional_plugin_model(label: str) -> bool: def netbox_utilities_tenant_required() -> bool: """Return the effective tenant policy without requiring the optional plugin.""" + if not apps.is_installed("netbox_utilities"): # importing its models while disabled raises RuntimeError + return False try: from netbox_utilities.runtime import tenant_required except ImportError: @@ -27,6 +31,19 @@ def netbox_utilities_tenant_required() -> bool: return bool(tenant_required()) +def netbox_utilities_tenant_messages() -> set[str]: + """Messages netbox_utilities may raise for a missing tenant, in the active language.""" + messages = {MISSING_TENANT_MESSAGE} + if not apps.is_installed("netbox_utilities"): + return messages + try: + from netbox_utilities.tenant_validation import VALIDATION_MESSAGE + except ImportError: + return messages + messages.add(str(VALIDATION_MESSAGE)) + return messages + + def is_tenant_relation(field) -> bool: if field.name != "tenant": return False @@ -99,7 +116,9 @@ class PluginCompatibility: @staticmethod def _is_missing_tenant_error(exc: ValidationError) -> bool: - return MISSING_TENANT_MESSAGE in exc.messages + if any(getattr(error, "code", None) == MISSING_TENANT_CODE for error in getattr(exc, "error_list", ())): + return True + return not netbox_utilities_tenant_messages().isdisjoint(exc.messages) def _auto_import_tenant(self): if self._fallback_tenant is not None: @@ -118,18 +137,24 @@ class PluginCompatibility: if self.dry_run: message = ( - 'Für den Prüflauf wurde der Mandant "Auto-Import" automatisch als Ersatzmandant ' - "verwendet; er wird nicht dauerhaft angelegt oder geändert." + _( + 'The tenant "Auto-Import" was used automatically as a fallback tenant for the dry run; ' + "it is not created or changed permanently." + ) ) elif created: message = ( - 'Der Mandant "Auto-Import" wurde automatisch erstellt und Objekten ohne ' - "auflösbaren Mandanten zugewiesen." + _( + 'The tenant "Auto-Import" was created automatically and assigned to objects without a ' + "resolvable tenant." + ) ) else: message = ( - 'Der vorhandene Mandant "Auto-Import" wurde automatisch für Objekte ohne ' - "auflösbaren Mandanten ausgewählt." + _( + 'The existing tenant "Auto-Import" was selected automatically for objects without a ' + "resolvable tenant." + ) ) self.warnings.append(message) self._fallback_tenant = tenant @@ -174,6 +199,9 @@ class PluginCompatibility: type(obj)._default_manager.filter(pk__in=conflict_ids).update(**{field.attname: None}) identifiers = ", ".join(str(pk) for pk in conflict_ids) self.warnings.append( - f"Eindeutige Referenz {obj._meta.label_lower}.{field_name} wurde von Zielobjekt(en) " - f"{identifiers} gelöst und dem importierten Objekt neu zugeordnet." + _( + "Unique reference %(field)s was released from target object(s) %(ids)s and reassigned to the " + "imported object." + ) + % {"field": f"{obj._meta.label_lower}.{field_name}", "ids": identifiers} ) diff --git a/netbox_export/services/references.py b/netbox_export/services/references.py index c522c46..3a61523 100644 --- a/netbox_export/services/references.py +++ b/netbox_export/services/references.py @@ -1,5 +1,7 @@ from __future__ import annotations +from django.utils.translation import gettext as _ + from .codec import decode_scalar from .exceptions import ArchiveValidationError @@ -25,7 +27,8 @@ class ReferenceResolver: fields = ", ".join(field_names) self.warn( ("skipped", record_id), - f"{record_id} ({model_label}) wurde wegen fehlender Pflichtreferenz übersprungen: {fields}.", + _("%(record)s (%(model)s) was skipped because of a missing required reference: %(fields)s.") + % {"record": record_id, "model": model_label, "fields": fields}, ) def _external_object(self, spec): @@ -39,14 +42,15 @@ class ReferenceResolver: value = model._default_manager.get(**lookup) except model.DoesNotExist: value = MISSING_REFERENCE - reason = "nicht gefunden" + reason = _("not found") except model.MultipleObjectsReturned: value = MISSING_REFERENCE - reason = "nicht eindeutig" + reason = _("not unique") if value is MISSING_REFERENCE: self.warn( ("external", cache_key), - f"Externe Referenz ausgelassen: {spec['model']} mit {lookup} ({reason}).", + _("External reference omitted: %(model)s with %(lookup)s (%(reason)s).") + % {"model": spec["model"], "lookup": lookup, "reason": reason}, ) self._external_cache[cache_key] = value return value @@ -59,10 +63,10 @@ class ReferenceResolver: if record_id in self.skipped: self.warn( ("internal", record_id), - f"Referenzen auf das übersprungene Objekt {record_id} wurden ausgelassen.", + _("References to the skipped object %(record)s were omitted.") % {"record": record_id}, ) return MISSING_REFERENCE, True return self.resolved.get(record_id), record_id in self.resolved if "external" in spec: return self._external_object(spec["external"]), True - raise ArchiveValidationError("Eine Objektreferenz im Archiv ist ungültig.") + raise ArchiveValidationError(_("An object reference in the archive is invalid.")) diff --git a/netbox_export/templates/netbox_export/dashboard.html b/netbox_export/templates/netbox_export/dashboard.html index 29e014a..d01ed7d 100644 --- a/netbox_export/templates/netbox_export/dashboard.html +++ b/netbox_export/templates/netbox_export/dashboard.html @@ -1,5 +1,6 @@ {% extends 'base/layout.html' %} {% load form_helpers %} +{% load i18n %} {% block title %}NetBox-Export{% endblock title %} @@ -19,18 +20,22 @@ {% if report %}
- + {% for model, counts in report.models.items %} @@ -50,7 +55,7 @@
-

Export

+

{% trans "Export" %}

{% csrf_token %} @@ -64,15 +69,15 @@
ModellErstelltAktualisiertÜbersprungen
{% trans "Model" %}{% trans "Created" %}{% trans "Updated" %}{% trans "Skipped" %}