官术网_书友最值得收藏!

Canonical URLs for models

You can use the post_detail URL that you have defined in the preceding section to build the canonical URL for Post objects. The convention in Django is to add a get_absolute_url() method to the model that returns the canonical URL of the object. For this method, we will use the reverse() method that allows you to build URLs by their name and passing optional parameters. Edit your models.py file and add the following:

from django.urls import reverse

class Post(models.Model):
# ...
def get_absolute_url(self):
return reverse('blog:post_detail',
args=[self.publish.year,
self.publish.month,
self.publish.day,
self.slug])

We will use the get_absolute_url() method in our templates to link to specific posts.

主站蜘蛛池模板: 广宁县| 林口县| 乡城县| 阜平县| 法库县| 凤山市| 陆良县| 嘉鱼县| 嘉定区| 宽甸| 丰都县| 邵武市| 安顺市| 潞城市| 微山县| 新余市| 昂仁县| 诸暨市| 客服| 揭东县| 铁岭县| 榆林市| 襄汾县| 兴业县| 绥滨县| 孟津县| 洛隆县| 嵊泗县| 南溪县| 长武县| 临漳县| 梅河口市| 密山市| 嘉鱼县| 金沙县| 电白县| 瓮安县| 三台县| 名山县| 得荣县| 黄冈市|