Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Generate default slug

I want to generate a random slug for my model, but without setting "blank=True" (as I want to enforce it later with validation.)

I was wondering if I could do something like this:

slug = models.SlugField(unique=True, default=some_method(), verbose_name='URL Slug')

Where some_method is a method which generates a random slug? I've tried the above code and it doesn't work :(

What I'd like to do is generate a unique slug (unique_slugify?)

like image 275
Hanpan Avatar asked Feb 03 '11 09:02

Hanpan


People also ask

How do you auto populate slug field in Django?

If you have built your own server-rendered interface with forms, you could auto-populate the fields by using either the |slugify tamplate filter or the slugify utility when saving the form (is_valid).

How do I add a slug field in Django?

Adding Slugify to our project: Now we need to find a way to convert the title into a slug automatically. We want this script to be triggered every time a new instance of Post model is created. For this purpose, we will use signals. Note: Add new file util.py in the same directory where settings.py file is saved.

What is Django slug?

A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They're generally used in URLs. ( as in Django docs) A slug field in Django is used to store and generate valid URLs for your dynamically created web pages.


1 Answers

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
like image 174
Prateek Avatar answered Oct 11 '22 15:10

Prateek