From 0a16a0bd9df78f8ab6396de4143f35f169709980 Mon Sep 17 00:00:00 2001 From: Philip Sargent Date: Sat, 22 Nov 2025 13:08:08 +0200 Subject: [PATCH] now doing dates and foreign keyed objects corretly --- core/utils.py | 6 ++--- core/views/logbooks.py | 55 +++++++++++++++++++++--------------------- 2 files changed, 30 insertions(+), 31 deletions(-) diff --git a/core/utils.py b/core/utils.py index c865d59..0a0ba0a 100644 --- a/core/utils.py +++ b/core/utils.py @@ -9,8 +9,8 @@ import resource import socket import string import subprocess -from datetime import datetime, timezone -from decimal import getcontext +from datetime import datetime, timezone, date +from decimal import getcontext, Decimal from pathlib import Path from django.contrib.auth.models import User @@ -540,7 +540,7 @@ class WriteAndCommitError(Exception): class CustomJSONEncoder(json.JSONEncoder): def default(self, obj): # Convert datetime objects to ISO 8601 string format - if isinstance(obj, datetime): + if isinstance(obj, (datetime, date)): return obj.isoformat() # Convert Decimal objects to string if isinstance(obj, Decimal): diff --git a/core/views/logbooks.py b/core/views/logbooks.py index c43519f..20389aa 100644 --- a/core/views/logbooks.py +++ b/core/views/logbooks.py @@ -2,8 +2,6 @@ import json import re from datetime import datetime -from decimal import Decimal - from django.contrib.auth.models import User from django.core.exceptions import ValidationError @@ -390,7 +388,7 @@ def logbook_entries_export(request, year): # print(f"{e.pk:03} {e}") editor = get_editor(request) - write_entries(entries, year, editor) + write_entries(entries[:6], year, editor) return redirect(f"/logreport/{year}") @@ -402,12 +400,11 @@ def write_entries(entries, year, editor): year - the year of the expo. """ - def write_json_file(): - # uses filepath, jsondict from context - + def write_json_file(jsondict): + # uses filepath, from context try: with open(filepath, 'w', encoding='utf-8') as json_f: - json.dump(jsondict, json_f, indent=1) + json.dump(jsondict, json_f, indent=1, cls=CustomJSONEncoder,) except PermissionError as e: raise PermissionError( f"CANNOT save this file.\nPERMISSIONS incorrectly set on server for this file {filepath}. Ask a nerd to fix this: {e}" @@ -422,24 +419,39 @@ def write_entries(entries, year, editor): author_link = PersonLogEntry.objects.select_related('personexpedition').get( logbook_entry=le, - is_logbook_entry_author=True # Adjust filter based on your logic + is_logbook_entry_author=True ) author = author_link.personexpedition.person - print(author) + + participants_links = PersonLogEntry.objects.select_related('personexpedition').filter( + logbook_entry=le, + is_logbook_entry_author=False + ) + participants = [] + for pl in participants_links: + participants.append(pl.personexpedition.person) + + author_data = model_to_dict(author, fields=['id', 'slug']) - jsondict = serialize("json", [le], fields=('slug', 'date', 'expedition', 'title', 'cave', 'place', 'other_people', 'time_underground', 'text')) - return jsondict + participants_data = [] + for p in participants: + participants_data.append(model_to_dict(p, fields=['id', 'slug'])) + + entrydict = model_to_dict(le, fields=('slug', 'date', 'expedition', 'title', 'cave', 'place', 'other_people', 'time_underground', 'text')) + entrydict['author'] = author_data + entrydict['participants_data'] = participants_data + return entrydict dirpath = settings.EXPOWEB / "years" / year / LOGBOOK_ENTRIES - for le in entries[:4]: + for le in entries: filename = f"{le.slug}-{le.pk:03}.json" filepath = dirpath / filename # description = f" {le.slug} :: {le.date} - {le.title}" ensure_dir_exists(filepath) - jsondict = serialize_logentry(le) - write_json_file() + entrydict = serialize_logentry(le) + write_json_file(entrydict) git_add(filename, dirpath) commit_msg = f"Exporting {len(entries)} logbook entries as individual files." @@ -448,20 +460,7 @@ def write_entries(entries, year, editor): def export_entry_with_author_details(request, entry_id): - try: - # 1. Get the LogbookEntry instance - entry = LogbookEntry.objects.get(pk=entry_id) - - # 2. Get the related PersonLogEntry and Person (Author) - # Use .select_related() for efficiency - author_link = PersonLogEntry.objects.select_related('person').get( - entry=entry, - is_author=True # Adjust filter based on your logic - ) - author = author_link.person - - except (LogbookEntry.DoesNotExist, PersonLogEntry.DoesNotExist): - return HttpResponse(f'Entry or Author not found for ID {entry_id}', status=404) + # 3. Manually create the nested dictionary structure # Use model_to_dict for easy extraction of the simple fields