【问题标题】:URL dispatcher: categories and draftsURL 调度程序:类别和草稿
【发布时间】:2020-10-22 20:28:54
【问题描述】:

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. 其他任何内容都通过以下网址进入 PostDetailView:

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

【问题讨论】:

  • 在我的架构中,任何帖子都有一个类别。

标签: django django-urls


【解决方案1】:

正则表达式的问题;

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 个或多个字符,但换行符除外。因此,要将帖子与 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/

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

【讨论】:

    猜你喜欢
    • 2012-06-21
    • 2016-04-08
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    • 2015-02-09
    • 1970-01-01
    相关资源
    最近更新 更多