修改 get_absolute_url的方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010377372/article/details/80409765

前言

在使用可复用的app的时候,get_absolute_url有时可能会没有定义,或者我们想要修改get_absolute_url的返回

方法

在django的settings.py中添加如下配置

ABSOLUTE_URL_OVERRIDES = {
    'blogs.weblog': lambda o: "/blogs/%s/" % o.slug,
    'news.story': lambda o: "/stories/%s/%s/" % (o.pub_year, o.slug),
}

其中的key由 app_label和model_name 组成。如果不知道app_label和model_name的话,可以在数据库中的 django_content_type表中查看。类似如下:

直接将其中的app_label和model对应起来即可。

比如我想修改 Topic 模型的get_absolute_url则对应的key是 forum_conversation.topic


猜你喜欢

转载自blog.csdn.net/u010377372/article/details/80409765