首页 > 解决方案 > 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/去索引工作正常,但我无法匹配整数。我真的很感激任何建议,在这一点上我非常非常困惑。

标签: djangodjango-viewsdjango-urls

解决方案


您的代码存在问题之一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

推荐阅读