size = 5 ''.join(random.choice(string.letters[26:] + string.digits) for in range(size))
this will generate some short code, but they can be duplicated. therefore, before saving, make sure that they are unique in your database.
def generate(size=5): code = ''.join(random.choice(string.letters[26:] + string.digits) for in range(size)) if check_if_duplicate(code): return generate(size=5) return code
or using a unique django restriction and exception handling.
source share