Reputation: 29805
I am trying to create unique slugs from persons names, which will have obvious duplicates. My idea is to add the id to the slug as a unique identifier. The problem is that the unique id is not generated until the save completes.
This is what I tried:
def save(self, *args, **kwargs):
if getattr(self, 'name', True):
if not self.pk:
matching_slugs = Entity.objects.filter(slug=slugify(self.name))
print matching_slugs
if len(matching_slugs) > 0:
self.slug=slugify(self.name+' temp')
elif len(matching_slugs) == 0:
self.slug=slugify(self.name)
super(Entity, self).save(*args, **kwargs)
self.slug=slugify(self.name+' '+str(self.id))
self.save()
I get the error:
maximum recursion depth exceeded in cmp
I'm thinking this is not the best way to do this.
How can I make names unique on save?
Upvotes: 2
Views: 708
Reputation: 29805
I changed the save() to be:
super(Entity, self).save(*args, **kwargs)
self.slug=slugify(self.name+' '+str(self.id))
super(Entity, self).save(*args, **kwargs)
Upvotes: 0
Reputation:
May be you can use simple construction?:
import uuid
def save(self, *args, **kwargs):
if not self.slug:
self.slug = "%s.%s" % (self.name , uuid.uuid4())
super(Entity, self).save(*args, **kwargs)
Upvotes: 3