Django Unique Link Generator

Using a random string generator, we will create unique links for any model.

from django.utils.text import slugify
random_string_generator can be found here::
from yourapp.utils import random_string_generator

def unique_slug_generator(instance, new_slug=None):
    This is for a Django project and it assumes your instance 
    has a model with a slug field and a title character (char) field.
    if new_slug is not None:
        slug = new_slug
        slug = slugify(instance.title)

    Klass = instance.__class__
    qs_exists = Klass.objects.filter(slug=slug).exists()
    if qs_exists:
        new_slug = "{slug}-{randstr}".format(
        return unique_slug_generator(instance, new_slug=new_slug)
    return slug

The above code assumes that your model looks like this at least:

class YourModel(models.Model):
    title = models.CharField(max_length=120)
    slug = models.SlugField(blank=True)

In any case, nothing will stop you from adding your own code to the generator. Good luck.

Back to Top