43 lines
1.2 KiB
Python
43 lines
1.2 KiB
Python
import string
|
|
import random
|
|
from django.utils.text import slugify
|
|
|
|
|
|
def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
|
|
return ''.join(random.choice(chars) for _ in range(size))
|
|
|
|
|
|
def unique_order_id_generator(inst):
|
|
"""
|
|
Generate unique order_id.
|
|
Model should have an order_id field to use this function.
|
|
"""
|
|
print('i am here')
|
|
order_new_id = random_string_generator()
|
|
|
|
Klass = inst.__class__
|
|
qs_exists = Klass.objects.filter(order_id =order_new_id).exists()
|
|
if qs_exists:
|
|
return unique_slug_generator(inst)
|
|
return order_new_id
|
|
|
|
|
|
def unique_slug_generator(inst, new_slug=None):
|
|
"""
|
|
Generate unique slug from title or based on provided slug.
|
|
Model should have a slug field and a title (char) field to use this function.
|
|
"""
|
|
if new_slug is not None:
|
|
slug = new_slug
|
|
else:
|
|
slug = slugify(inst.title)
|
|
|
|
Klass = inst.__class__
|
|
qs_exists = Klass.objects.filter(slug=slug).exists()
|
|
if qs_exists:
|
|
new_slug = "{slug}-{randstr}".format(
|
|
slug=slug,
|
|
randstr=random_string_generator(size=4)
|
|
)
|
|
return unique_slug_generator(inst, new_slug=new_slug)
|
|
return slug |