|
|
|
@ -196,35 +196,16 @@ class Hadis(LowercaseSlugMixin, models.Model): |
|
|
|
|
|
|
|
def save(self, *args, **kwargs): |
|
|
|
self.clean() |
|
|
|
# Generate slug if not already set or if slug is empty |
|
|
|
|
|
|
|
# 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') |
|
|
|
|
|
|
|
# Fallback if no title text exists |
|
|
|
if not self.slug or (isinstance(self.slug, str) and self.slug.strip() == ''): |
|
|
|
title_text = None |
|
|
|
|
|
|
|
# 1. Try to extract text if title exists |
|
|
|
if self.title and isinstance(self.title, list) and len(self.title) > 0: |
|
|
|
first_item = self.title[0] |
|
|
|
if isinstance(first_item, dict): |
|
|
|
title_text = first_item.get("text") |
|
|
|
|
|
|
|
# 2. If we found text, use smart slug |
|
|
|
if title_text: |
|
|
|
self.slug = generate_smart_slug( |
|
|
|
text=title_text, |
|
|
|
model_class=Hadis, |
|
|
|
max_length=100, |
|
|
|
keep_words=8, |
|
|
|
instance=self, |
|
|
|
) |
|
|
|
# 3. CRITICAL FALLBACK: If no title text, use the number with unique suffix |
|
|
|
else: |
|
|
|
# We use a random suffix or timestamp to ensure uniqueness if multiple untitled hadiths exist |
|
|
|
from datetime import datetime |
|
|
|
import random |
|
|
|
import time |
|
|
|
# Use timestamp + random to ensure uniqueness |
|
|
|
suffix = int(time.time() * 1000) % 1000000 # Use milliseconds for better uniqueness |
|
|
|
suffix = int(time.time() * 1000) % 1000000 |
|
|
|
base_slug = f"hadis-{self.number or 'unknown'}-{suffix}" |
|
|
|
# Ensure uniqueness by checking database |
|
|
|
counter = 1 |
|
|
|
while Hadis.objects.filter(slug=base_slug).exclude(pk=self.pk).exists(): |
|
|
|
base_slug = f"hadis-{self.number or 'unknown'}-{suffix}-{counter}" |
|
|
|
|