Automate unique slug (again)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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

More like this

  1. YAAS (Yet Another Auto Slug) by carljm 5 years ago
  2. Automate unique slugs by taojian 5 years, 5 months ago
  3. Model Forms: Clean unique field by johnboxall 4 years, 5 months ago
  4. Auto-rename duplicate fields by christian.oudard 3 years, 9 months ago
  5. unique_together with many to many fields by j4nu5 1 year, 8 months ago

Comments

davidwtbuxton (on May 17, 2008):

Damn, forget to change 'Publication' to 'MyModel' for the example.

Other slug fight examples: http://www.djangosnippets.org/tags/slug/

#

(Forgotten your password?)