python - django 当前路径 image/25x25 与这些都不匹配

标签 python django

我正在使用 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/

相关文章:

python - 删除所有内容包括列表中不等于所需字符串的所有空格

django 在模板中使用媒体 URL

Django UserProfile匹配查询不存在

Django:最有效的多对多关系添加,无需通过模型?

django - 上传的图片不显示,路径错误

python - Haystack - 'SearchQuerySet' 对象没有属性 'model'

python - 通过在 PyQt4 中选择/取消选择 QStandardItemModel 在 matplotlib 中显示/隐藏线条

python - 如何在 Python 中获取嵌套函数的命名空间?

python - 在多线程中调用 Py_Initialize()

python - 匹配除特定字符串之外的所有内容