In this post we are going to know how to generate unique slug in django automatically. So what is slug? Consider the URL of this post: /auto-generating-unique-slug-in-django/ . Here the bold part of the URL is called slug.
First, consider a model Article
in which we will generate the unique slug.
|
|
In our model Article
we have three fields: title, slug and content. Django provides a built-in model field for slug, SlugField
. We will generate the slug based on the title field.
How the slug will be generated: If the title of our first article is ‘New article’, the slug will be ’new-article’. If the title of our second article is also ‘New article’, the slug will be ’new-article-1’. And if the title of our third article is ‘New article’ again, the slug will be ’new-article-2’. And so on.
So, to do that we have to write code like this:
|
|
Look at the line 22, we override the save()
method here. If the slug doesn’t already exist in the instance of Article, we generate it by calling _get_unique_slug()
method. I am not explaining the code of _get_unique_slug()
method in detail because it is kind of self explanatory. But what slugify()
does? Well, if we give a string like ‘The new article title’ to slugify()
, it returns ’the-new-article-title’. Simple.
You can also consider to use the pre_save signal instead of overriding the save method.
Thanks for reading this post. Have a nice day!
You should consider to read this post as well: Auto generating unique slug in Django: a generic approach.