How to create a unique slug in Django
I use this snippet for generating unique slug and my typical save method look like below
slug will be Django SlugField with blank=True but enforce slug in save method.
typical save method for Need model might look below
def save(self, **kwargs): slug_str = "%s %s" % (self.title, self.us_zip) unique_slugify(self, slug_str) super(Need, self).save(**kwargs)
and this will generate slug like buy-a-new-bike_Boston-MA-02111 , buy-a-new-bike_Boston-MA-02111-1 and so on. Output might be little different but you can always go through snippet and customize to your needs.
My little code:
def save(self, *args, **kwargs): strtime = "".join(str(time()).split(".")) string = "%s-%s" % (strtime[7:], self.title) self.slug = slugify(string) super(Need, self).save()
If you are thinking of using an app to do it for you, here is one.
https://github.com/un33k/django-uuslug
UUSlug = (``U``nique + ``U``code Slug)Unicode Test Example=====================from uuslug import uuslug as slugifys = "This is a test ---"r = slugify(s)self.assertEquals(r, "this-is-a-test")s = 'C\'est déjà l\'été.'r = slugify(s)self.assertEquals(r, "c-est-deja-l-ete")s = 'Nín hǎo. Wǒ shì zhōng guó rén'r = slugify(s)self.assertEquals(r, "nin-hao-wo-shi-zhong-guo-ren")s = '影師嗎'r = slugify(s)self.assertEquals(r, "ying-shi-ma")Uniqueness Test Example=======================Override your objects save method with something like this (models.py)from django.db import modelsfrom uuslug import uuslug as slugifyclass CoolSlug(models.Model): name = models.CharField(max_length=100) slug = models.CharField(max_length=200) def __unicode__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name, instance=self) super(CoolSlug, self).save(*args, **kwargs)Test:=====name = "john"c = CoolSlug.objects.create(name=name)c.save()self.assertEquals(c.slug, name) # slug = "john"c1 = CoolSlug.objects.create(name=name)c1.save()self.assertEquals(c1.slug, name+"-1") # slug = "john-1"