django---url---03

url 自定义转换器

在app文件下建立conver.py文件

class Conver:
    regex = r'[0-9]{4}'
    def to_python(self,value):
        return int(value)
    def to_url(self,value):
        return str(value)

regex = 为固定值,后面跟正规表达式

def to_python(返回给视图), to_url固定函数名(反向解析用)

在项目文件下建立url

from app.conver import Conver

register_converter(Conver,'YYYY')   注册url并使用

path('acticles/<YYYY:year>/',views.article_2019)  路径

from mysite.conver import Conver
register_converter  (Conver,'YYYY')
urlpatterns = [
    path('acticles/<YYYY:year>/',views.article_2019)
]

view 内容

def article_2019(request,year):
    return HttpResponse(year)

页面展示

http://127.0.0.1:8000/acticles/2009/

猜你喜欢

转载自www.cnblogs.com/ljf520hj/p/11700505.html