美文网首页
用在URL中的slug

用在URL中的slug

作者: 叶田的学习笔记 | 来源:发表于2018-10-16 23:26 被阅读0次

    安装 awesome-slugify

    sudo pip install awesome-slugify

    models.py 建立数据模型

    from django.db import models
    from django.contrib.auth.models import User
    from django.utils import timezone
    from django.urls import reverse
    
    from slugify import slugify
    
    class ArticlePost(models.Model):
        author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='article')
        title = models.CharField(max_length=200)
        slug = models.SlugField(max_length=500)
        created = models.DateTimeField(default=timezone.now)
        updated = models.DateTimeField(auto_now=True)
       
        class Meta:
            ordering = ['-updated']
            index_together = ['id','slug']
    
        def __str__(self):
            return self.title
    
        def save(self,*args,**kwargs):        #   ①
            self.slug = slugify(self.title)         #   ②
            super(ArticlePost,self).save(*args,**kwargs)
    
        def get_absolute_url(self):
            return reverse("article:article_detail",args=[self.id,self.slug])
    

    每个数据模型类都有一个save()方法,语句①对此方法进行重写,其目的就是要实现语句②。

    urlconf配置如下

    re_path(r'^article-detail/(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.article_detail, name="article_detail"),
    

    注意正则表达式的写法,awesome-slugify生成的slug中间有连接符“-”。

    相关文章

      网友评论

          本文标题:用在URL中的slug

          本文链接:https://www.haomeiwen.com/subject/gfbkzftx.html