我正在尝试学习 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中设置你的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
]
总之,方便的解决方案是slash(/)
在 urls.py 文件中添加路径。喜欢:
path('monthlyreport/', include('monthlyreport.url'))
|
|
|
V
Add slash here
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句