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.
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
from django.db import models | |
from django.dispatch import receiver | |
from django.db.models.signals import pre_save | |
from .utils import unique_slug_generator | |
class SomeModel(models.Model): | |
title = models.CharField(max_length=400) | |
slug = models.SlugField(max_length=400, null=True, blank=True, unique=True) | |
def __str__(self): | |
return self.title | |
@receiver(pre_save, sender=SomeModel) | |
def pre_save_receiver(sender, instance, *args, **kwargs): | |
if not instance.slug: | |
instance.slug = unique_slug_generator(instance) | |
utils.py
import string, random | |
from django.utils.text import slugify | |
def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits): | |
return ''.join(random.choice(chars) for _ in range(size)) | |
def unique_slug_generator(instance, new_slug=None): | |
if new_slug is not None: | |
slug = new_slug | |
else: | |
slug = slugify(instance.title) | |
Klass = instance.__class__ | |
max_length = Klass._meta.get_field('slug').max_length | |
slug = slug[:max_length] | |
qs_exists = Klass.objects.filter(slug=slug).exists() | |
if qs_exists: | |
new_slug = "{slug}-{randstr}".format( | |
slug=slug[:max_length - 5], randstr=random_string_generator(size=4)) | |
return unique_slug_generator(instance, new_slug=new_slug) | |
return slug |
path('test/<slug:slug>/', views.your_view_goes_here, name='your path name goes here'),urls.py
0 Comments