![]() |
VOOZH | about |
The slug field in Django models helps create clean and readable URLs for web pages. It generates URL-friendly text based on titles or similar fields.
Consider a project named 'blog' having an app named 'posts'. For a blog post titled “The Django book by GeeksforGeeks” with primary key id=2, the post may be referenced using:
www.geeksforgeeks.org/posts/2.
Or, can reference the title like:
www.geeksforgeeks.org/posts/The Django book by Geeksforgeeks.
But the problem is spaces are not valid in URLs, they need to be replaced by %20, which is ugly, making it the following:
www.geeksforgeeks.org/posts/The%20Django%20book%20by%20geeksforgeeks
But it is not solving meaningful URL. Another option can be:
www.geeksforgeeks.org/posts/the-django-book-by-geeksforgeeks
So, the slug is now the-django-book-by-geeksforgeeks. All letters are down cased and spaces are replaced by hyphens.
The slug field, represented as models.SlugField in Django models, is used to store a URL-friendly version of a text-based field, such as a title. Its primary purpose is to create cleaner, more readable, and search engine-friendly URLs for content.
A method is required to convert the title into a slug automatically, and this process should run whenever a new Post instance is created. To achieve this, signals are used.
Add new file util.py in the same directory where settings.py file is saved.
In many cases, when a model instance is modified, an action must be executed.
In models.py file of posts app where Post Model was defined, add this in the same file:
The pre_save_receiver function should be placed separately outside the Post model.
To modify your urls.py file to use the slug field in Django model for generating URLs, create URL patterns that include the slug as a parameter:
This 'detail' view function in Django takes a 'slug' parameter from the URL and searches for a post with a matching slug in a case-insensitive manner.
In urls.py edit detail path with path('posts/<slug:slug>/', views.detail). In views.py edit the detail function with:
The last step is to add the link in HTML file <a href="/posts/{{ a.slug }}" class="btn btn-primary">View</a>. Now ready to go to 127.0.0.1:8000/posts/title-you-have-added and it will show the page details.html.