How to create a unique slug in Django

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

    Here are a couple functions that I use. You pass in the model instance and the desired title into unique_slugify which will add the slug if it doesn't exist, otherwise it will continue trying to append a 4 digit random string until it finds a unique one.

    import string
    from django.utils.crypto import get_random_string
    
    def unique_slugify(instance, slug):
        model = instance.__class__
        unique_slug = slug
        while model.objects.filter(slug=unique_slug).exists():
            unique_slug = slug + get_random_string(length=4)
        return unique_slug
    

    I usually use it by overriding the model save method.

    class YourModel(models.Model):
        slug = models.SlugField()
        title = models.CharField()
    
        def save(self, *args, **kwargs):
            if not self.slug:
                self.slug = unique_slugify(self, slugify(self.title))
            super().save(*args, **kwargs)
    

提交回复
热议问题