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 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-10-26 21:26:52 +01:00
1 parent 409b239fca
commit 72e04fe086
21 files changed
+713 -156

No files matched your search

+21 -20
View File
@@ -12,6 +12,7 @@ from pathlib import PurePosixPath
from typing import BinaryIO
from django.core.serializers.json import DjangoJSONEncoder
from django.utils.translation import gettext as _
from .exceptions import ArchiveValidationError
@@ -54,7 +55,7 @@ def build_archive(manifest: dict, records: Iterable[dict], assets: dict[str, byt
for path, content in assets.items():
safe_path = _safe_member_name(path)
if safe_path in normalized_assets:
raise ArchiveValidationError(f"Doppelter Dateipfad im Archiv: {safe_path}")
raise ArchiveValidationError(_("Duplicate file path in archive: %(path)s") % {"path": safe_path})
normalized_assets[safe_path] = content
assets = normalized_assets
object_data = b"\n".join(_json_bytes(record) for record in records) + b"\n"
@@ -94,7 +95,7 @@ def build_archive(manifest: dict, records: Iterable[dict], assets: dict[str, byt
def _safe_member_name(name: str) -> 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)
+5 -2
View File
@@ -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:
+61 -44
View File
@@ -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
+38 -10
View File
@@ -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}
)
+10 -6
View File
@@ -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."))