from django.db import models, IntegrityError
class MyModel(models.Model):
def save(self):
"""Auto-populate an empty slug field from the MyModel name and
if it conflicts with an existing slug then append a number and try
saving again.
"""
import re
from django.template.defaultfilters import slugify
if not self.slug:
self.slug = slugify(self.name) # Where self.name is the field used for 'pre-populate from'
while True:
try:
super(MyModel, self).save()
# Assuming the IntegrityError is due to a slug fight
except IntegrityError:
match_obj = re.match(r'^(.*)-(\d+)$', self.slug)
if match_obj:
next_int = int(match_obj.group(2)) + 1
self.slug = match_obj.group(1) + '-' + str(next_int)
else:
self.slug += '-2'
else:
break
Comments
Damn, forget to change 'Publication' to 'MyModel' for the example.
Other slug fight examples: http://www.djangosnippets.org/tags/slug/
#