Search Here

Making Perfect SEO Friendly URL in Django Using Slug

 In this article, you will learn how to make a perfect human-readable URL like (https://xyz.com/how-to-make-a-perfect-url-in-django), instead of putting id (https://xyz.com/1) in Django. To do this we are going to use Django built-in FieldType (SlugField) in our custom model.

Making Perfect SEO Friendly URL in Django Using Slug

What is Slug in Django

In Django slug is a short scripted label for some text, title, or string. A slugify string or text contains only letters, numbers, hyphens, or underscores. For example, we have a title field in a model, and the text of this title has "Learn Openerp", then in terms of a slug this title field will convert into "learn-openerp".

Read More: Post Request Via Ajax in Django CSRF Token Missing or Incorrect

Why do we use a slug in Django

In Django to create a perfect and human-readable URL, we can use the slug. Django provides a "SlugField" type field to store slug values. By using this field we can generate or store a valid dynamic URL for our web pages.

Enjoy Free Tools: SEO Optimised Url Length Checker For All Pages

Read More: How to Create Apps in Django Project

What if we can not use slug

For example, if we have a title like this (Learn Openerp). Then in URL this title will be automatically replaced by Learn%20Openerp, this is not a good practice. As we know that we can not add a space in the URL, so to overcome this issue we will use the slug to make a human-readable URL.

Read More: Heroku & Github Error: item could not be retrieved unauthorized

Example of URL Before applying slug

https://xyz.com/1

Example of URL Before applying slug

https://xyz.com/how-to-make-a-perfect-url-in-django

Step by step guide to making a perfect URL instead of id

Below is the step-by-step guide to making a perfect URL using the slug in Django. 

The above code to make a URL with hyphens has the following features.

  • Create a unique slug
  • Convert the title automatically into slug using signals
  • Whenever a change in title field slug field will automatically update its value
  • If the slug field is empty, then just save the value again using the admin panel to apply changes in the slug field
Enjoy Free Tools: Online SEO Friendly URL Analyzer Tool

Create a field named "slug" with field type "SlugField"

models.py


Create a python field named "utils" in your Django app

utils.py


In the app, in urls file modify your path (url) like below.

path('test/<slug:slug>/', views.your_view_goes_here, name='your path name goes here'),
urls.py
After that, just run the below command in the terminal to change your database.

python manage.py makemigrations
python manage.py migrate

Post a Comment

0 Comments