From c6e528104c9222d7db975b51a5152a670e96340d Mon Sep 17 00:00:00 2001 From: mohsentaba Date: Thu, 22 Oct 2026 08:33:14 +0330 Subject: [PATCH] feat(arguments): auto fill arguments title with related source title. --- apps/hadis/models/hadis.py | 23 +++++++++++++++++++++++ apps/hadis/views_admin.py | 13 +++++++++++++ 2 files changed, 36 insertions(+) diff --git a/apps/hadis/models/hadis.py b/apps/hadis/models/hadis.py index 14d7d1a..c64e6ef 100644 --- a/apps/hadis/models/hadis.py +++ b/apps/hadis/models/hadis.py @@ -254,10 +254,33 @@ class Hadis(LowercaseSlugMixin, models.Model): return False + @staticmethod + def _has_localized_value(value): + return isinstance(value, list) and any( + isinstance(x, dict) and str(x.get('text', '') or x.get('title', '')).strip() + for x in value + ) + + def auto_populate_title(self): + """ + Auto-fills self.title if empty, using the title of the first linked BookReference (source). + """ + if self._has_localized_value(self.title): + return False + if self.pk: + ref = self.references.filter(book_reference__isnull=False).select_related('book_reference').order_by('id').first() + if ref and ref.book_reference and self._has_localized_value(ref.book_reference.title): + self.title = ref.book_reference.title + return True + return False def save(self, *args, **kwargs): self.clean() + # Auto-fill title from the first source (book reference) if empty + if not self._has_localized_value(self.title): + self.auto_populate_title() + # Automatically generate or update smart slug when title changes from utils.slug import build_slug_for_instance build_slug_for_instance(self, source_field='title') diff --git a/apps/hadis/views_admin.py b/apps/hadis/views_admin.py index 8aeb403..66dc990 100644 --- a/apps/hadis/views_admin.py +++ b/apps/hadis/views_admin.py @@ -1526,6 +1526,19 @@ class AdminHadisReferenceViewSet(ModelViewSet): return qs.order_by("id") + def _sync_hadis_title(self, instance): + # If the argument has no title, fill it from the first source's book title + hadis = getattr(instance, "hadis", None) + if hadis and not Hadis._has_localized_value(hadis.title): + if hadis.auto_populate_title(): + hadis.save() + + def perform_create(self, serializer): + self._sync_hadis_title(serializer.save()) + + def perform_update(self, serializer): + self._sync_hadis_title(serializer.save()) +