Here's some code that I wrote a few days ago:

class MyModel(models.Model):
    #various fields and stuff here

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = self.make_slug()
        super(Project, self).save(*args, **kwargs)

    def make_slug(self):
        """ Create a (unique) slug from self.name. """
        sanitized = re.sub("(?i)[^a-z0-9_-]", "_", self.name).lower()
#remove non-alpha-numeric-underscore-hyphen chars
        sanitized = re.sub("^_|_$", "", sanitized) #remove underscores
from start/end cos they look dumb
        while(re.search("__", sanitized)): #remove double underscores
cos they look dumb
            sanitized = re.sub("__", "_", sanitized)
        #now make sure that it's unique:
        while(Project.objects.filter(slug__iexact=sanitized).count()):
#if it's not unique
            current_number_suffix_match = re.search("\d+$", sanitized)
#get the current number suffix if there is one
            current_number_suffix = current_number_suffix_match and
current_number_suffix_match.group() or 0
            next = str(int(current_number_suffix) +1) #increment it,
and turn back to string so re.sub doesn't die
            sanitized = re.sub("(\d+)?$", next, sanitized) #replace
current number suffix with incremented suffix, try again...
        return sanitized

That should do exactly what you're after.
Adam Alton

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to