Login

Automate unique slug (again)

Author:
davidwtbuxton
Posted:
May 17, 2008
Language:
Python
Version:
.96
Score:
2 (after 2 ratings)

This takes the "easier to ask forgiveness than permission" approach to making sure your model's slug is unique.

If the model's slug is empty, make a slug from the model's 'name' field.

We assume that it is a conflicting slug that is throwing the IntegrityError, in which case if the slug does not end with '-' followed by a number then append '-2'. If the slug does end with '-' followed by a number then capture that final number, increment it by one, save the new slug value and try savin g 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.