在Django中使用path()找不到404 [英] Getting 404 not found using path() in Django
问题描述
我刚刚签出django,并试图通过将 id
作为URL books / urls的参数传递来列出书籍.py
。但是却找不到404页面错误。在浏览器中键入此URL时,URL没有出问题:
I was just checking out django, and was trying a view to list the books by passing id
as an argument to the URL books/urls.py
. But getting 404 page not found error. I'm not getting whats wrong in the url when I typed this url in the browser:
http://192.168.0.106:8000/books/list/21/
bookstore / urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('books/', include("books.urls"))
]
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'books'
]
...
...
...
ROOT_URLCONF = 'bookstore.urls'
books / urls.py
urlpatterns = [
path('home/', create),
path('list/(?P<id>\d+)', list_view),
]
书/视图。 py
def create(request):
form = CreateForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "Book Created")
return redirect('/books/list', kwargs={"id":instance.id})
return render(request, "home.html", {"form":form})
def list_view(request, id=None):
books = Book.objects.filter(id=id)
return render(request, "list.html", {"books": books})
项目结构:
├── books
│ ├── admin.py
│ ├── forms.py
│ ├── __init__.py
│ ├── models.py
│ ├── urls.py
│ └── views.py
├── bookstore
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
这是屏幕截图-
编辑-如注释中所述-在 books.urls $的url表达式中附加
/
c $ c>但没有运气:(
EDIT - As addressed in the comments - Tried by appending /
in the url expression of thebooks.urls
but no luck :(
推荐答案
Django 2.0中新的路径
错误。您不应该使用 \d +
这样的正则表达式。尝试将其更改为:
You are using the new path
from Django 2.0 incorrectly. You shouldn't use a regex like \d+
. Try changing it to:
path('list/<int:id>/', list_view, name='list_view'),
名称
是必需的想要反转URL。
The name
is required if you want to reverse the URL.
如果您想使用正则表达式,请使用 re_path
(或<$ c如果您想与旧版Django兼容,$ c> url()仍然可以使用。有关更多信息,请参见 URL分派器文档。
If you want to stick with regexes, then use re_path
(or url()
still works if you want to be compatible with older versions of Django). See the URL dispatcher docs for more info.
还要注意尾部的斜杠-否则您的路径匹配 http://192.168.0.106:8000/books/list/21
,但不是 http://192.168.0.106:8000/books/list/21/
。
Note the trailing slash as well - otherwise your path matches http://192.168.0.106:8000/books/list/21
but not http://192.168.0.106:8000/books/list/21/
.
这篇关于在Django中使用path()找不到404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!