Django教程,页面未找到< int:question_id>

fafcakar  于 2023-03-24  发布在  Go
关注(0)|答案(3)|浏览(94)

我的views.py

from django.http import HttpResponse, Http404
from django.shortcuts import render, get_object_or_404

from .models import Question

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

我的urls.py

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('/', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
]

当我去'http://127.0.0.1:8000/polls/1/'我收到'页面找不到'错误,但我肯定有这个问题_id,我可以看到这个问题_id在 shell ,它不重要什么ID我写我总是收到同样的问题。
Image from my web browser

5gfr0r5j

5gfr0r5j1#

好的。也许你的django应用程序没有连接到站点?

  • your_site/your_site/urls.py*
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]
qlzsbp2j

qlzsbp2j2#

我已经找到答案了,我只需要在我的

path('/<int:question_id>/', views.detail, name='detail')

这看起来像是Django文档中一些错误。非常感谢大家的关注!

hgc7kmma

hgc7kmma3#

app_name正在命名路径的名称,但不更改url。这应该可以做到:

urlpatterns = [
    path('/', views.index, name='index'),
    path('/polls/<int:question_id>/', views.detail, name='detail'),
]

相关问题