How To Create Django Unique Slug , Warning Of Duplicate slug

What is Django unique slug

In Django Unique Slug , a slug is a short label or unique label used to identify a particular resource, often a page or an entry in a database. It’s typically used in URLs to create human-readable and search engine-friendly URLs.The human readable there have define everything.

A slug is usually derived from the title or name of the resource by converting it into a URL-friendly format.This means that without slug your url could have been example.com/2 and so on, remember there is no space for this.

Then this involves removing spaces, special characters, and converting letters to lowercase. For example, the title “Python Django”: An Example of Blog” would be converted to the slug “python-django-an-example-of-blog”.

In this article slugs are commonly used to generate clean and meaningful URLs for pages or objects. Instead of users to be seeing post ID like 54 or 3 they would be seeing a friendly id.

They improve the usability of the website and can also enhance search engine optimization (SEO) by including relevant keywords in the URL.

Django framework has done this already it is just for to use it , django provides the tools to automatically generate and manage slugs for your models, making it easier to handle website or blogs

What is Django unique slug with no duplicate

With the above definitions and and explanations django unique is a means in which there would be no same slug in django every post would have the same slug.

What is Django unique slug with no duplicate warning

In this post if a user tries to use the same slug or title there would be a warning if same slug is used.

There would be a case where you wouodn’t want users to enter slug manually therefore , if same slug is used a warning wouod be issuesmd.

Again if the slug is not hidden and the user tries to input slug manually since there is warning already then instead of the system to reject the post , seeing that the post is important then we would use an increment.

Example. If a slug is python-django

and some one come again and write python-django the system will install it as python-django-1

, another person own would python-django-2 and so on


Steps to implement unique slug with no duplicate and warning to users

1. Define a Slug Field with unique=True in your model.
2. Generate a unique slug in the save() method or using a pre-save signal.
3. If the generated slug already exists, modify it to ensure uniqueness by appending a counter.


Lets get started

In Django, ensuring unique slugs with no duplicates can be achieved by combining the use of a slug field with the pre-save signal or by overriding the save() method of your model.

Illustration of how to implement unique slug with no duplicate

1. Define a SlugField

In your model, define a SlugField where you willl store the slug value. Use the unique=True parameter to ensure uniqueness.

from django.db import models
from django.utils.text import slugify

class Blog(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255,unique=True,blank=True)
    # ... other fields ...

In this case the blank True will help us to prepopulate our slug from the real time. If you that add the blank true it may require you to add slug manually.

Generate a Unique Slug

In OUR model We can use save() method or using a pre-save signal, to generate a unique slug from the title. If the generated slug already exist then our argurement will come up.

Using save() method


from django.db import models
from django.utils.text import slugify

class Blog(models.Model):
    title = models.CharField(max_length=255,blank=False)
    slug = models.SlugField(blank=True,max_length=255,unique=True)
    # ... other fields ...

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        
        original_slug = self.slug
        counter = 1
        while Blog.objects.filter(slug=self.slug).exclude(pk=self.pk).exists():
            self.slug = f"{original_slug}-{counter}"
            counter += 1
        
        super().save(*args, **kwargs)

We can also use this method


from django.db import models
from django.utils.text import slugify

class Blog(models.Model):
    
    # ... Your models fields ...

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        
            original_slug = self.slug
            counter = 1
            while Blog.objects.filter(slug=self.slug).exists():
            self.slug = f"{original_slug}-{counter}"
            counter += 1
        
        super().save(*args, **kwargs)

The method would not take empty slug it would prompt you to type in slug before it could check for duplicates

Now you can play around with the code above , the below codes is what brought you here , feel free to copy it and adjust to your taste remember that indentation matters in python.


How to implement unique slug and warn user users of duplicate slug

from django.db import models
from django.utils.text import slugify
#other imports here


#this model is for django
class Blog(models.Model):
    slug = models.SlugField(unque=True,blank=True,max_length=255)
    title = models.CharField(blank=False,max_length=255)


    #other arguments here

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = orig = slugify(self.title)
            counter = 1
            while Blog.objects.filter(slug=self.slug).exists():
                self.slug = f"{orig}-{counter}"
                counter += 1
        super().save(*args, **kwargs)

    def __str__(self):
        return self.title
    

With this code you will be able to type in your title and save without the manually typing of the slug.

Django Superuser : How To Create Superuser In Django by benchatronics

Now there is one more we will do , i dont like javascripts excepts for some reasons that are necessary , we will be implementing slug prepopulation in our admin dash board. to prepopulate slugin real time we have to edith our admin.py and include a file named signals.py in our code.

Create a file name it signals.py and include the following codes


from django.utils.text import slugify
from django.dispatch import receiver
from django.db.models.signals import pre_save
from .models import Blog

@receiver(pre_save,sender=Blog)
def prepopulate_slug(sender,instance,**kwargs):
      if not instance.slug:
            instance.slug = slugify(instance.topic)
  

Now you have to also edit your admin.py and the following code inside of it

@admin.register(Blog)
class BlogAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug':('title',)}

Now let us add an external edit interface where we can add blog

in your views.py add the following codes using class base view

from django.views.generic import CreateView
#orther imports

class PostView(CreateView):
    model = Brainy
    template_name = 'add_post.html'
    form_class = PostForm

Then do not forget to add the html page and also the url mapping , you can also include the hidden type for slug so that you can not see the slug as you type.

How to commit a project on Github using Termux and Android

One thought on “How To Create Django Unique Slug , Warning Of Duplicate slug

Leave a Reply

Your email address will not be published. Required fields are marked *