I use Django 1.11 and the parler plugin for translation. Every time I save a slug, I wish to
- test if it already exists
- truncate the slug
- add number
- test again, if the new slug exists and so on
This way, I wish to create a unique slug on saving.
models.py:
from parler.models import TranslatableModel
from django.utils.translation import gettext_lazy as _
class Event(TranslatableModel):
translations = TranslatedFields(
event_title=models.CharField(_("event title"), max_length=512),
slug=models.SlugField(_("slug"), help_text=_("Used in the URL of the event page.")),
description=RichTextUploadingField(blank=True),
meta={'unique_together': (('language_code', 'slug'),)},
)
def save_translation(self, translation, *args, **kwargs):
"""Create a unique slug of 45 Characters + a dash and 4 digits."""
translation.slug = translation.slug[:50]
if Event.objects.active_translations(slug=translation.slug).exists():
# This is true on the first test for no apparent reason.
i = 0
while Event.objects.active_translations(slug=translation.slug).exists():
translation.slug = translation.slug[:44]+'-'+str(i)
i += 1
super(Event, self).save_translation(translation, *args, **kwargs)
This code dosen't work. It always add a number to the slug, no matter what, even if I enter a completely new slug.
The problem here is that save_translation gets called multiple times. My solution is:
It got a bit longer then I hoped, but I think it works.