class Slugged(models.Model): """ Abstract model that handles auto-generating slugs. Each slugged object is also affiliated with a specific site object. """ title = models.CharField("Title", max_length=10000) slug = models.CharField("URL", max_length=20000, blank=True, null=True, help_text=("Leave blank to have the URL auto-generated from " "the title.")) class Meta: abstract = True def __str__(self): return self.title def save(self, *args, **kwargs): """ If no slug is provided, generates one before saving. """ if not self.slug: self.slug = self.generate_unique_slug() super(Slugged, self).save(*args, **kwargs) def generate_unique_slug(self): """ Create a unique slug by passing the result of get_slug() to utils.urls.unique_slug, which appends an index if necessary. """ # For custom content types, use the ``Page`` instance for # slug lookup. concrete_model = base_concrete_model(Slugged, self) return unique_slug(self.get_slug()) def get_slug(self): """ Allows subclasses to implement their own slug creation logic. """ from django.utils.text import slugify title = self.title.replace(u'ı', u'i') # Check if the instance is of the Question model model_class = self.__class__.__name__ if model_class == "Question": title = title[:75] return slugify(title) def base_concrete_model(abstract, instance): for cls in reversed(instance.__class__.__mro__): if issubclass(cls, abstract) and not cls._meta.abstract: return cls return instance.__class__ def unique_slug(slug): """ Ensures a slug is unique for the given queryset, appending an integer to its end until the slug is unique. """ hash_suffix = hashlib.md5().hexdigest()[:8] new_slug = f"{hash_suffix}" print(f'SLUG: {slug+"-"+new_slug} ') return slug+"-"+new_slug