我正在尝试学习 Django,浏览了官方教程并自己尝试了一下。我创建了一个新应用程序,可以访问索引页面,但无法使用模式匹配转到任何其他页面。这是我的
monthlyreport/url.py
from django.urls import path
from . import views
#app_name = 'monthlyreport'
urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id>/', views.detail, name='detail'),
]
还有我的
monthlyreport/views
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic
from .models import Report
def index(request):
report_list = Report.objects.all()[:5]
template = loader.get_template('monthlyreport/index.html')
context = {
'report_list': report_list,
}
return HttpResponse(template.render(context, request))
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
显示 http://127.0.0.1:8000/monthlyreport/0 的调试
Using the URLconf defined in maxhelp.urls, Django tried these URL patterns, in this order:
monthlyreport [name='index']
monthlyreport <int:question_id>/ [name='detail']
polls/
admin/
accounts/
The current path, monthlyreport/0, didn’t match any of these.
再次,使用 http://127.0.0.1:8000/monthlyreport/ 去索引工作正常,但我无法匹配整数。我真的很感激任何建议,我现在非常非常困惑。
您的代码的问题在于一个
slash(/)
。在您的根 urls.py
文件中,您必须使用类似以下内容:
path('monthlyreport', include('monthlyreport.url'))
所以,这里的问题是,如果您在
monthlyreport.url中设置网址,则路径中应该以
/
结尾,例如:
urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id>/', views.detail, name='detail'),
]
否则,你必须将
slash(/)
放在每个新路径的前面,例如:
urlpatterns = [
path('', views.index, name='index'),
path('/<int:question_id>/', views.detail, name='detail'),
|
|
V
Here
]
总而言之,方便的解决方案是在 urls.py 文件中的路径后面添加
slash(/)
。喜欢:
path('monthlyreport/', include('monthlyreport.url'))
|
|
|
V
Add slash here
这可以帮助您解决错误