[Fixed]-Django – Generate default slug

10πŸ‘

βœ…

You could override the models save-method so that when a new entity is created, you generate the slug on the fly. Something like:

if not self.pk:
    self.slug = ''.join(random.sample(string.ascii_lowercase, 10))

You could do that, but it isn’t very good and better would be to let the slug be a deterministic slugified version of the objects name.

27πŸ‘

You can use this when you want your slug to be generated automatically with the entry made in some other field in the same model, where the slug lies.

from django_extensions.db.fields import AutoSlugField

slug = AutoSlugField(_('slug'), max_length=50, unique=True, populate_from=('name',))
  • populate_from is the field in the model which will auto generate the slug
πŸ‘€Prateek

5πŸ‘

default has to be a value or a callable.
So it’s default=some_method, not default=some_method(). Here is an example:

from django.contrib.auth.models import UserManager

def randomString():
    um = UserManager()
    return( um.make_random_password( length=25 ) )

class Foo( models.Model ):
    code = models.CharField( max_length=25, default=randomString )
πŸ‘€BigJ

1πŸ‘

maybe model validation can help? http://docs.djangoproject.com/en/dev/ref/models/instances/

You can just simple validate the value which should be written in a slug field and if it exists already, generate something unique.

Also overriding of the models save method could be the solution.

Cheers.

1πŸ‘

searching in google, I found similar question: How to use slug in django

I think so the better approach is rewrite the save method, and validade the field in form.

But, slug should be unique, so generate random string is not good! Like Tommaso Bardugi say early, if you add the timestamp in url, this is resolved.

Leave a comment