Browse Source

feat(arguments): auto fill arguments title with related source title.

master
Mohsen Taba 1 week ago
parent
commit
c6e528104c
  1. 23
      apps/hadis/models/hadis.py
  2. 13
      apps/hadis/views_admin.py

23
apps/hadis/models/hadis.py

@ -254,10 +254,33 @@ class Hadis(LowercaseSlugMixin, models.Model):
return False 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): def save(self, *args, **kwargs):
self.clean() 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 # Automatically generate or update smart slug when title changes
from utils.slug import build_slug_for_instance from utils.slug import build_slug_for_instance
build_slug_for_instance(self, source_field='title') build_slug_for_instance(self, source_field='title')

13
apps/hadis/views_admin.py

@ -1526,6 +1526,19 @@ class AdminHadisReferenceViewSet(ModelViewSet):
return qs.order_by("id") 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())

Loading…
Cancel
Save