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 - 在 Django 中通过 id 获取对象

python - Django-URL 命名空间

python - 以 timedelta 为条宽的条形图

python - Django 管理仪表板,无法记录 "select all"

python - PyCharm 中的远程解释器和本地绘图?

python - django:提供静态 Assets *无需*复制它们(收集静态)

python - 使用 django 下载文件

django - 使用 {% url ??? %} 在 Django 模板中

python - TensorFlow:在 while 循环中堆叠张量

python - Pandas :根据是否为 ​​NaN 移动列