Top

Django Slug Tutorial: Readable URLs

Aug 03, 2020 | 645 views

#Django

Refer to

urls.py 

urlpatterns = [ 
    path('post/<str:slug>', views.post_detail, name='post_detail'),
]

The code refer from https://github.com/Radi85/django-website.git, under its section blog/models.py


class Post(models.Model):  
    ... 
    slug = models.SlugField(max_length=200, null=False, unique=True,                             
                            blank=True, verbose_name="Slug (Not required)")
    def set_slug(self):                                                                          
        if not self.slug:                                                                
        # if Post.objects.filter(slug__isnull=True):                                     
            # Newly created object, so set slug                                          
            _title = self.title                                                              
            unique_slug = self.slug = slugify(_title, allow_unicode=True)                
            count = 1                                                                                
            # Keep checking if the new generated slug exists                             
            while Post.objects.filter(slug=unique_slug).exists():
                unique_slug = "{}-{}".format(self.slug, count)                           
                count += 1                                                                           
            self.slug = unique_slug                                                                                                                                                   
    def save(self, *args, **kwargs):                                                     
        self.set_slug()
        super(Post, self).save(*args, **kwargs)                                                  


Leave a comment

1 comments

Jack Aug. 4, 2020, midnight

Very nice!