DJango 尝试在 blog.html 上查找索引号时出现正则表达式错误

2024-02-08

我在尝试使用 Django 加载特定索引号(与博客文章相关)时出现以下错误。

错误代码如下- 谁能帮忙指出错误吗?

        path(r'(?P)<pk>\d+)', DetailView.as_view(model = Post,template_name = 'blog/post.html'))

urls.py 文件中显示上下文的完整代码如下:

from django.urls import path
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post


#it's already going to blog/, so this regular expression is just blank

urlpatterns = [

        path(r'', ListView.as_view(queryset=Post.objects.all().order_by("-date") [:25], 
                                                       template_name="blog/blog.html")),

        path(r'(?P)<pk>\d+)', DetailView.as_view(model = Post,template_name = 'blog/post.html'))

] 我试图访问的 URL 是:

http://127.0.0.1:8000/blog/2

并且页面上的错误是:

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/blog/2
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
blog/
blog/ (?P)<pk>\d+)
The current path, blog/2, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

简而言之,我需要帮助来查找以下代码片段中的错误(第一个路径工作正常,第二个路径则不然)

urlpatterns = [

        path(r'', ListView.as_view(queryset=Post.objects.all().order_by("-date") [:25], 
                                                       template_name="blog/blog.html")),

        path(r'(?P)<pk>\d+)', DetailView.as_view(model = Post,template_name = 'blog/post.html'))

]

UPDATE我将代码更改为删除错误的括号:

path(r'(?P<pk>\d+)', DetailView.as_view(model = Post,template_name = 'blog/post.html'))]

但还是不行...

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
blog/
blog/ (?P<pk>\d+)
The current path, blog/2, didn't match any of these.

尝试建议的答案我尝试使用这个,但错误仍然存​​在

urlpatterns = [

        path(r'', ListView.as_view(queryset=Post.objects.all().order_by("-date") [:25], 
                                                       template_name="blog/blog.html")),

                path(r'<int:pk>\d+', DetailView.as_view(model = Post,template_name = 'blog/post.html'))]

并尝试过这个:

path(r'(?P<int:pk>\d+', DetailView.as_view(model = Post,template_name = 'blog/post.html'))]

除此之外:

path(r'(?P<int:pk>\d+)', DetailView.as_view(model = Post,template_name = 'blog/post.html'))]

错误仍然存​​在

  Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
blog/
blog/ (?P<int:pk>\d+)
The current path, blog/2, didn't match any of these.

问题是您对旧的基于正则表达式的 URL 机制和新的基于路径的机制感到困惑。如果你使用path,您应该使用新的特殊语法:

path('<int:pk>', DetailView.as_view(...))

而如果你想使用正则表达式,你应该使用旧的url函数(或新的别名,re_path):

url(r'(?P<pk>\d+)', DetailView.as_view(...))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

DJango 尝试在 blog.html 上查找索引号时出现正则表达式错误 的相关文章

随机推荐