首页 > 解决方案 > 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工作正常。

标签: pythondjango

解决方案


您需要从路由定义中删除括号。它应该如下所示:

path('image/<int:width>x<int:height>/', placeholder, name='placeholder'),

使用(Django 2.0 中的新功能)的路由定义path()不再使用正则表达式,因此您不需要像过去使用传统url()定义那样将参数括在括号中来捕获正则表达式组。此外,您不需要r前缀,因为您没有使用任何特殊字符,而且您不太可能使用它们,因为您再次没有使用正则表达式。

更多信息可以在文档path()中找到。


推荐阅读