What is a “slug” in Django?

前端 未结 10 1784
感情败类
感情败类 2020-11-22 14:59

When I read Django code I often see in models what is called a \"slug\". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is th

10条回答
  •  轮回少年
    2020-11-22 15:21

    Slug is a URL friendly short label for specific content. It only contain Letters, Numbers, Underscores or Hyphens. Slugs are commonly save with the respective content and it pass as a URL string.

    Slug can create using SlugField

    Ex:

    class Article(models.Model):
        title = models.CharField(max_length=100)
        slug = models.SlugField(max_length=100)
    

    If you want to use title as slug, django has a simple function called slugify

    from django.template.defaultfilters import slugify
    
    class Article(models.Model):
        title = models.CharField(max_length=100)
    
        def slug(self):
            return slugify(self.title)
    

    If it needs uniqueness, add unique=True in slug field.

    for instance, from the previous example:

    class Article(models.Model):
        title = models.CharField(max_length=100)
        slug = models.SlugField(max_length=100, unique=True)
    

    Are you lazy to do slug process ? don't worry, this plugin will help you. django-autoslug

提交回复
热议问题