Update web/core/views.py

This commit is contained in:
2025-08-22 02:54:30 +00:00
parent 2648467bb1
commit 4b54275780
+36 -8
View File
@@ -348,26 +348,54 @@ def import_wizard(request):
try: try:
raw = form.cleaned_data["file"].read() raw = form.cleaned_data["file"].read()
# --- header check (tolerant: utf-8-sig removes BOM, strip spaces, case-insensitive) --- # --- superdefensive header peek (never raises) ---
import io, csv as _csv import io, csv as _csv
sio = io.StringIO(raw.decode("utf-8-sig", errors="replace")) sio = io.StringIO(raw.decode("utf-8-sig", errors="replace"))
header_ok = False
try:
rdr = _csv.reader(sio) rdr = _csv.reader(sio)
first_row = next(rdr, []) first_row = next(rdr, [])
norm = [c.strip().lower() for c in first_row]
expected_norm = [c.lower() for c in _EXPECTED_HEADERS]
# If the first row doesnt look like our header, allow import to proceed, def _clean(s):
# but show a gentle warning in the result page. s = "" if s is None else str(s)
# strip quotes and odd prefixes like r:"Talk Title"
s = s.strip().strip("'").strip('"')
if s.lower().startswith("r:"):
s = s[2:].lstrip()
return s.strip().lower()
norm = [_clean(c) for c in first_row]
# Pull expected headers from globals if defined, else use defaults
expected = (
globals().get("_EXPECTED_HEADERS")
or globals().get("EXPECTED_HEADERS")
or [
"Subject", "Illustration", "Application", "Scripture", "Source",
"Talk Title", "Talk Number", "Code", "Date", "Date Edited",
]
)
expected_norm = [h.strip().lower() for h in expected]
header_ok = (norm == expected_norm) header_ok = (norm == expected_norm)
except Exception:
header_ok = False
finally:
# Rewind so the real importer reads the full file
sio.seek(0)
# Make sure the utils module also knows the expected headers
from . import utils as core_utils
if not hasattr(core_utils, "EXPECTED_HEADERS"): if not hasattr(core_utils, "EXPECTED_HEADERS"):
core_utils.EXPECTED_HEADERS = _EXPECTED_HEADERS core_utils.EXPECTED_HEADERS = expected
# hand off to your existing robust importer
# Hand off to your robust importer
report = import_csv_bytes( report = import_csv_bytes(
raw, raw,
dry_run=form.cleaned_data["dry_run"], dry_run=form.cleaned_data["dry_run"],
) )
# attach header check info (if your template shows report dicts) # Attach header check info for the result template
report = report or {} report = report or {}
report["header_ok"] = header_ok report["header_ok"] = header_ok
if not header_ok: if not header_ok: