django - URL 与 Django 中的 url 模式不匹配
问题描述
我正在尝试学习 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
推荐阅读
- angular - 角 9 SSR | 无法访问 ads.txt 文件
- postgresql - 如何在 PostgreSQL 中通过 cmd 使用 pg_restore 命令恢复 .bak 文件?
- unity3d - 为子像素阴影映射编码几何信息
- python - 如何处理 Python Selenium 中的“消息:过时的元素引用:元素未附加到页面文档”
- javascript - Javascript - 为存储在用户计算机上的静态网页读取/写入设置的推荐/安全方式是什么?
- html - 为什么叠加的图片和标志+文字不起作用?
- ruby-on-rails - 与乘客一起在生产中使用 resque 时,没有路线匹配 [GET] "/resque/overview"
- c++ - 在字符串中查找模式
- google-apps-script - Google-App-Scripts-Search files 找不到电子表格
- highcharts - Highchart甘特图删除Y轴标签