Django - 详细视图 URL 中的模型 ID,第一个 ID 不工作
Django - Model id in Detail View URL, 1st id not working
我有一个模型,Position
,我创建了一个详细视图来查看每个单独的位置。
views.py
def position_detail_view(request, id=None):
position = get_object_or_404(Position, id=id)
context= {
'object': position,
}
return render(request, 'positions/position_detail.html', context)
positions/urls.py
from django.urls import path, include
from .views import position_list_view, position_detail_view
urlpatterns = [
path('', position_list_view),
path('<int:id>', position_detail_view, name='detail')
]
当我转到 http://localhost:8000/apply/1/,id=1 时,我收到页面未找到 404 错误。但是,使用任何其他 id,页面加载都很好。关于为什么模型中的第一个 id 给出 404 错误的任何想法?
Edit 1: Traceback Error
Page not found (404) Request Method: GET Request
URL: http://localhost:8000/apply/1/ Using the URLconf defined in
bta_website.urls, Django tried these URL patterns, in this order:
admin/ [name='home'] apply/application/ apply/ apply/
[name='detail'] The current path, apply/1/, 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.
Django get_object_or_404
的工作方式如下。
get_object_or_404(klass, *args, **kwargs)
在给定的模型管理器上调用 get(),但它引发了 Http404 而不是模型的 DoesNotExist 异常。
在你的情况下,
您的 URL 路径配置不正确。
尝试做出这样的改变:
path('/<int:id>/', position_detail_view, name='detail')
我有一个模型,Position
,我创建了一个详细视图来查看每个单独的位置。
views.py
def position_detail_view(request, id=None):
position = get_object_or_404(Position, id=id)
context= {
'object': position,
}
return render(request, 'positions/position_detail.html', context)
positions/urls.py
from django.urls import path, include
from .views import position_list_view, position_detail_view
urlpatterns = [
path('', position_list_view),
path('<int:id>', position_detail_view, name='detail')
]
当我转到 http://localhost:8000/apply/1/,id=1 时,我收到页面未找到 404 错误。但是,使用任何其他 id,页面加载都很好。关于为什么模型中的第一个 id 给出 404 错误的任何想法?
Edit 1: Traceback Error
Page not found (404) Request Method: GET Request URL: http://localhost:8000/apply/1/ Using the URLconf defined in bta_website.urls, Django tried these URL patterns, in this order:
admin/ [name='home'] apply/application/ apply/ apply/ [name='detail'] The current path, apply/1/, 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.
Django get_object_or_404
的工作方式如下。
get_object_or_404(klass, *args, **kwargs)
在给定的模型管理器上调用 get(),但它引发了 Http404 而不是模型的 DoesNotExist 异常。 在你的情况下, 您的 URL 路径配置不正确。 尝试做出这样的改变:
path('/<int:id>/', position_detail_view, name='detail')