python - Django 2 url路径匹配负值

标签 python django django-urls

在 Django <2 中,通常的做法是使用正则表达式。但是现在在 Django => 2 中推荐使用 path() 而不是 url()

path('account/<int:code>/', views.account_code, name='account-code')

这看起来不错,并且可以很好地匹配 url 模式

/account/23/
/account/3000/

但是,这个问题是我也希望它匹配像

这样的负整数
/account/-23/

请问我如何使用 path() 执行此操作?

最佳答案

你可以写custom路径转换器:

class NegativeIntConverter:
    regex = '-?\d+'

    def to_python(self, value):
        return int(value)

    def to_url(self, value):
        return '%d' % value

在 urls.py 中:

from django.urls import register_converter, path

from . import converters, views

register_converter(converters.NegativeIntConverter, 'negint')

urlpatterns = [
    path('account/<negint:code>/', views.account_code),
    ...
]

关于python - Django 2 url路径匹配负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48867977/

相关文章:

python - Pandas 哈希表 KeyError

python - 我如何在某种意义上 ndarrays 中的 "juggle"元素?

python - 为什么 Python 3 需要用 list() 包裹 dict.items?

python - 使用 BeautifulSoup 无法访问 div

python - Django HayStack 从 URL 获取参数并相应更新默认查询

python - 如何将两个参数传递给 url(不使用 GET)?

python - 编码给出 "' ascii' 编解码器无法编码字符......序号不在范围内(128)“

python - 自定义小部件的验证

mysql - Django 全文搜索 mysql

python - Django - 当前 URL 与这些中的任何一个都不匹配