Commits

Lucian Brănescu-Mihăilă  committed e856390

Fix bug with slugs, where numbers were being appended instead of just incremented (like hello-world-1-2-3)

  • Participants
  • Parent commits 8f2ad7e

Comments (0)

Files changed (2)

 - nice UI
 - pagination in index
 - tests. I still can't get djangoappengine to run my tests, complains about wrong app_label. Stupid django.
+- comments
+import re
+
 from django.template.defaultfilters import slugify
-
 from django.db import models
 
 
         else:
             return self.content
 
-    def get_unique_slug(self, title):
+    @classmethod
+    def get_unique_slug(cls, title):
+        '''Sadly, django-norel/appengine can't handle slug__iregex. Even though
+        Django's sqlite backend uses the re module for regexes anyway, since
+        sqlite has no such native support.
+
+        Writing this function, I could really have used 
+        '''
+
         potential = slugify(title)
-        suffix = 0
 
-        while True:
-            if suffix:
-                potential = "{}-{}".format(potential, suffix)
+        slugs = (i.slug for i in cls.objects\
+                                    .filter(slug__startswith=potential))
 
-            if not Blog.objects.filter(slug=potential).count():
-                return potential
-            
-            suffix += 1
+        similar = re.compile(r'^{0}-(\d+)$'.format(potential))
+
+        has_potential = False
+        collisions = []
+        for i in slugs:
+            if i == potential:
+                has_potential = True
+
+            r = similar.match(i)
+            if r:
+                collisions.append(int(r.groups()[0]))
+        
+        if not has_potential:
+            return potential
+        
+        return '{0}-{1}'.format(potential, max(collisions) + 1)
 
     def save(self, *args, **kwargs):
         if not self.slug: