我在尝试使用 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.