我正在使用 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'),
使用path()
的路由定义(Django 2.0 中的新功能)不再使用正则表达式,因此您不需要像传统的 url()
那样将参数括在括号中。用于捕获正则表达式组的定义。另外你也不需要r
前缀,因为您没有使用任何特殊字符,并且您不太可能使用它们,因为您没有使用正则表达式。
更多信息可以在docs on path()
中找到.
关于python - django 当前路径 image/25x25 与这些都不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52455119/