fields.py 691 B

12345678910111213141516171819202122
  1. import random
  2. import string
  3. from django_extensions.db.fields import AutoSlugField
  4. class OrganizationSlugField(AutoSlugField):
  5. """
  6. Generate a random alphanumeric slug starting at length 2.
  7. Increase length by 1 if collision is found.
  8. """
  9. def slug_generator(self, original_slug, start):
  10. yield original_slug
  11. for i in range(start, self.max_unique_query_attempts):
  12. yield original_slug + "-" + "".join(
  13. random.choices(string.ascii_lowercase + string.digits, k=i)
  14. )
  15. raise RuntimeError(
  16. "max slug attempts for %s exceeded (%s)"
  17. % (original_slug, self.max_unique_query_attempts)
  18. )