如何使用 Django 将页面标题置于 url 模式中?

How to put the page title in a url pattern with Django?

如果我想将博文 ID 发送到 url 模式,并让 url 自动变成类似 www.blog.com/post/2/this-is-my-second-blogpost 的内容,我该怎么做?

在 urls.py 内部,我有一个 url 接受博文 ID 及其标题的模式。它似乎不起作用,一旦起作用,以这种方式为每个页面添加标题会很乏味。

urls.py:path('post/<int:post_id>/<str:post_title>', views.view_post, name='view_post'),

blogposts.html 模板: <a href="{% url 'blogs:view_post' post.id post.title%}">Read More</a>

views.py: def view_post(request, post_id, post_title):.

简单地说,将post_title的默认参数添加为None。如果您希望直接从 post_id 获取 post_title,请忽略 post_title,这样做不会给您带来错误,因为函数已经获得了所有满足的参数值。

所以:

def view_post(request, post_id, post_title=None):

编辑

好的,用户想要的是slug field。 Slug field是django模型中的字段类型。基本上,它用于 url 类型。在上面的问题中,pyknight202 想要的是 post_title 的 url 模式。因此,您不能将 tilte 直接用作 url,因为它们包含空格,因此您必须在连字符或下划线中添加 post_title 才能可读。因此,您需要 Post 模型中的 slug 字段。

https://helloworld.com/1/this-is-example

因此,1 是 post_id,因为 slug 不可能是唯一的,所以您不仅可以从 post_title 检索,因此您也需要 post_idRefs

也许您应该为 url 使用 slug 字段而不是 ID 和标题的组合,您的 url 看起来像 example.org/title-to-object-2/。 现在您有一个带有标题和 ID 的唯一 slug 字段。