URL 调度员:类别和草稿

URL dispatcher: categories and drafts

Django 3.0.7

urls.py

urlpatterns = [
    path(
        '<slug:categories>/',
        include(('categories.urls', "categories"), namespace="categories")
    ),
]

categories/urls.py

urlpatterns = [
    path('', CategoryView.as_view(), name='list'),
    re_path(r'.+', include(('posts.urls.post', "posts"), namespace="posts")),
]

这是我编写正则表达式以捕获不少于一个任意符号的错误尝试。

posts/urls/post.py

urlpatterns = [
    path('draft/<slug:slug>/', PostDetailView.as_view(), name="draft_detail"),
    path('<slug:slug>/', PostDetailView.as_view(), name="detail"),
]

第一个问题

当我加载 http://localhost:8000/linux/install-os-ubuntu/ 时,我得到这个:

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/linux/install-os-ubuntu/
Using the URLconf defined in pcask.urls, Django tried these URL patterns, in this order:

[name='home']
^admin/
polls/
applications/
draft/authors/
authors/
email/
facts/
<slug:categories>/ [name='list']
<slug:categories>/ .+ draft/<slug:slug>/ [name='draft_detail']
<slug:categories>/ .+ <slug:slug>/ [name='detail']
tags/ [name='tags']
__debug__/
^media/(?P<path>.*)$
^static/(?P<path>.*)$
^static/(?P<path>.*)$
The current path, linux/install-os-ubuntu/, didn't match any of these.

另一个问题

>>> p = Post.objects.first()
>>> p.get_absolute_url()
'/news/.efremov/'

那是url中出现的一个点。

这是怎么回事,我该如何组织:

  1. http://localhost:8000/linux/ 路由到 CategoryView。

  2. 任何其他内容都将通过 url 发送到 PostDetailView,例如:

    • http://localhost:8000/linux/draft/install-os-ubuntu/
    • http://localhost:8000/linux/install-os-ubuntu/

你遇到的问题是正则表达式;

re_path(r'.+', include(('posts.urls.post', "posts"), namespace="posts")),

为了说明问题,在上述路径中包含以下路径;

urlpatterns = [
    path('draft/<slug:slug>/', PostDetailView.as_view(), name="draft_detail"),
    path('<slug:slug>/', PostDetailView.as_view(), name="detail"),
]

posts 包括匹配除换行符外的 1 个或多个字符。因此,要将 post 与 slug my-post 匹配,您将拥有以下 URL;

/a/my-post/

/b/my-post/

/c/my-post/

我认为这里的正则表达式引起了混淆。为了将此与您的示例相匹配;

a) http://localhost:8000/linux/a/draft/install-os-ubuntu/

b) http://localhost:8000/linux/b/install-os-ubuntu/

我会做的是像这样设置您的 URL;

类别;

urlpatterns = [
    path('list/', CategoryView.as_view(), name='list'),
    path('', include(('posts.urls.post', "posts"), namespace="posts")),
]

同样值得注意的是,您可以在此处测试您的正则表达式; https://regexr.com/

它甚至会解释你的正则表达式在做什么,这通常是无价的,因为它们并不简单!!