How to create a unique slug in Django

后端 未结 12 499
栀梦
栀梦 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:57

    I use this snippet for generating unique slug and my typical save method look like below

    slug will be Django SlugField with blank=True but enforce slug in save method.

    typical save method for Need model might look below

    def save(self, **kwargs):
        slug_str = "%s %s" % (self.title, self.us_zip) 
        unique_slugify(self, slug_str) 
        super(Need, self).save(**kwargs)
    

    and this will generate slug like buy-a-new-bike_Boston-MA-02111 , buy-a-new-bike_Boston-MA-02111-1 and so on. Output might be little different but you can always go through snippet and customize to your needs.

提交回复
热议问题