Getting 404 not found using path() in Django

ε祈祈猫儿з 提交于 2019-12-03 18:12:02

问题


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),
]

books/views.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})

Project Structure:

├── books
│   ├── admin.py
│   ├── forms.py
│   ├── __init__.py
│   ├── models.py
│   ├── urls.py
│   └── views.py
├── bookstore
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py

Here is the screenshot -

EDIT - As addressed in the comments - Tried by appending / in the url expression of thebooks.urls but no luck :(


回答1:


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'),

The name is required if you want to reverse the 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.

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/.



来源:https://stackoverflow.com/questions/47334486/getting-404-not-found-using-path-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!