Auto slug field

 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
from django.db.models import fields
from django.template.defaultfilters import slugify

def unique_slug(model, slug_field, slug_value):
    orig_slug = slug = slugify(slug_value)
    
    index = 0
    
    while True:
        try:
            model.objects.get(**{slug_field: slug})
            index += 1
            slug = orig_slug + '-' + str(index)
        except model.DoesNotExist:
            return slug

class AutoSlugField(fields.SlugField):
    def pre_save(self, model_instance, add):
        if self.prepopulate_from:
            if self.unique:
                return unique_slug(model_instance.__class__, self.name, getattr(model_instance, self.prepopulate_from[0]))
            else:
                return slugify(getattr(model_instance, self.prepopulate_from[0]))
        else:
            return super(AutoSlugField, self).pre_save(model_instance, add)

More like this

  1. auto image field w/ prepopulate_from & default by zbyte64 4 years, 9 months ago
  2. Hierarchical page slugs by baumer1122 5 years, 9 months ago
  3. Automatically slugify slug fields in your models by Aliquip 6 years, 2 months ago
  4. Making prepopulate_from work with ForeignKeys and other sorts of choice fields by josho 4 years, 8 months ago
  5. YAAS (Yet Another Auto Slug) by carljm 4 years, 12 months ago

Comments

kujemanee (on April 28, 2008):

slug = models.SlugField(unique=True,prepopulate_from=('title',))

not enough ?

#

jefurii (on April 28, 2008):

This would make it easier to do automated testing. Slug fields have always errored out for me, and this snippet looks like it would address that.

#

GaretJax (on May 4, 2008):

@kujemanee Using a simple SlugField the values is prepopulated only in the admin interface trough javascript. Using AutoSlugField the value is automatically retrieved by each saving if necessary and adapted to be unique

#

chachra (on February 6, 2009):

setattr(model_instance, slug_field, slug)

before returning the slug value would be nice too, otherwise new instances of the model created do not have it set, for that request at least, although persists just fine to the db.

Wasted an hour cause of this! :) Thanks for the snippet!

#

Ciantic (on January 20, 2010):

I opened ticket #12651 to Django for this, IMO there are way too many auto/unique slug things in djangosnippets for example that one at least should be part of Django.

If you'd like to see unique/auto slug thing for Django, I suggest you drop your opinions there.

#

Ciantic (on January 20, 2010):

I've re-created this here for Django 1.x also tried to ensure that no length is exceeded etc.

#

(Forgotten your password?)