Skip to content

Commit

Permalink
fix the slugify method to ensure unique
Browse files Browse the repository at this point in the history
  • Loading branch information
nmenezes0 committed Jan 2, 2025
1 parent 79c8125 commit 2269ed5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
19 changes: 13 additions & 6 deletions consultation_analyser/consultations/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import datetime
import itertools
import random
import uuid
from dataclasses import dataclass

Expand Down Expand Up @@ -352,13 +352,20 @@ class SlugFromTextModel(models.Model):
slug = models.SlugField(null=False, editable=False, max_length=256)

def save(self, *args, **kwargs):
# Generate a slug from the text - ensure unique
cropped_length = 124
# Generate a slug from the text - ensure unique by adding timestamp if needed
ModelClass = self.__class__
cropped_length = 220
cropped_text = self.text[:cropped_length]
generated_slug = slugify(cropped_text)
ModelClass = self.__class__
while ModelClass.objects.filter(slug=generated_slug).exists():
generated_slug = f"{generated_slug[:cropped_length]}-{random.randint(0, 999)}"
if self.pk:
slug_exists = (
ModelClass.objects.filter(slug=generated_slug).exclude(pk=self.pk).exists()
)
else:
slug_exists = ModelClass.objects.filter(slug=generated_slug).exists()
if slug_exists:
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S%f")
generated_slug = f"{generated_slug}-{timestamp}"
self.slug = generated_slug
return super().save(*args, **kwargs)

Expand Down
4 changes: 2 additions & 2 deletions tests/unit/models/test_slug.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def test_consultation_save():
consultation_title = "My First Consultation"
slugified = "my-first-consultation"
consultation = Consultation2Factory(text=consultation_title)
assert consultation.slug.startswith(slugified)
assert consultation.slug == slugified
another_consultation = Consultation2Factory(text=consultation_title)
assert another_consultation.slug != consultation.slug
assert another_consultation.slug.startswith(slugified)
Expand All @@ -19,7 +19,7 @@ def test_question_save():
question_text = "What are your thoughts on the proposed changes?"
slugified = "what-are-your-thoughts-on-the-proposed-changes"
question = Question2Factory(text=question_text)
assert question.slug.startswith(slugified)
assert question.slug == slugified
another_question = Question2Factory(text=question_text)
assert another_question.slug != question.slug
assert another_question.slug.startswith(slugified)

0 comments on commit 2269ed5

Please sign in to comment.