python - django 当前路径,image/25x25,不匹配任何这些
问题描述
我正在使用 Django 2.1.1 。这是我的manage.py
文件:
import os
import sys
from django.conf import settings
settings.configure(
ROOT_URLCONF=__name__,
MIDDLEWARE_CLASSES=(
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
),
)
from django import forms
from django.urls import path
from django.http import HttpResponse, HttpResponseBadRequest
def placeholder(request, width, height):
...
if : ...
return HttpResponse('OK')
def index(request):
return HttpResponse('Hello World')
urlpatterns = [
path(r'image/(<int:width>)x(<int:height>)/', placeholder, name='placeholder'),
path(r'', index, name='homepage'),
]
当我浏览时127.0.0.1:8000/image/10x10
,发生了这个错误:
Using the URLconf defined in __main__, Django tried these URL patterns, in this order:
The current path, image/25x25, didn't match any of these
我认为我的代码是正确的;那么发生了什么?
可能是因为没有使用合适的中间件吗?
127.0.0.1:8000
工作正常。
解决方案
您需要从路由定义中删除括号。它应该如下所示:
path('image/<int:width>x<int:height>/', placeholder, name='placeholder'),
使用(Django 2.0 中的新功能)的路由定义path()
不再使用正则表达式,因此您不需要像过去使用传统url()
定义那样将参数括在括号中来捕获正则表达式组。此外,您不需要r
前缀,因为您没有使用任何特殊字符,而且您不太可能使用它们,因为您再次没有使用正则表达式。
更多信息可以在文档path()
中找到。
推荐阅读
- c# - 使用 JSON.NET 反序列化带有 IEnumerable 的对象
- android - 如何从android中的适配器访问活动内部视图?
- android - Android应用层方向
- json - 检查多个组合查询mongodb
- mysql - 在 Cloud Foundry 上将 Mysql 绑定到 Magnolia cms
- r - 如何查找哪个 URI 具有每个闪亮的应用程序选项卡
- neo4j - Neo4j 删除 N 关系
- inno-setup - 在卸载时删除任务计划程序任务?
- c# - 无法连接 AX 2009 Dynamics 业务连接器
- sql-server - 使用休眠在 JPQL 中调用用户定义的 SQL 函数