在 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/