django 自定义路由converter
详细步骤:
1.新建py文件,写一个类(类名随意),然后需要写一个名为regex的属性,其为正则匹配项,同时需要定义to_python和to_url两个函数,注意函数名不可改变。例如:
class FourDigitYearConverter:
regex = '[0-9]{4}'
def to_python(self, value):
return int(value)
def to_url(self, value):
return '%04d' % value
2.在 url.py 注册,自己的转换器,需要从django.urls导入register_converter注册函数,最后,调用该函数进行注册,例如:
from django.urls import register_converter
from . import convetors
register_converter(convetors.FourDigitYearConverter, 'year')
3.自定义转换器的使用,例如:
urlpatterns = [
path('test/<year:year>/',views.test),]
在浏览器中输入http://localhost:8000/test/3000/即可。