How to create a unique slug in Django

后端 未结 12 559
栀梦
栀梦 2020-12-04 22:17

I am trying to create a unique slug in Django so that I can access a post via a url like this: http://www.example.com/buy-a-new-bike_Boston-MA-02111_2

The relevant m

12条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 22:42

    This is the simple and small code i am using for generating unique slug, you only need one field to create your unique slug field

    from random import randint
    
    def save(self, *args, **kwargs):
        if Post.objects.filter(title=self.title).exists():
            extra = str(randint(1, 10000))
            self.slug = slugify(self.title) + "-" + extra
        else:
            self.slug = slugify(self.title)
        super(Post, self).save(*args, **kwargs)
    

    I hope you like this.

提交回复
热议问题