[Answered ]-Django – Generate shortest random slug

2πŸ‘

At a basic level, you could do this:

import random
import string 

def rand_slug():
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(6))


class Articles(models.Model):
    slug = models.CharField(max_length=6, unique=True, default=rand_slug())

Above will generate a random slug that is 6 characters long. By using unique=True on your model, it will make sure no other Article object has that slug.

If you want to take a more advanced approach, I would recommend generating this slug in a model manager by writing your own create method. You can then make the random slug have a dynamic size value, character set, etc.

πŸ‘€jape

Leave a comment