django---url---03

url custom converters

Establish conver.py file in the app file

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

regex = fixed value, followed by a regular expression

def to_python (return to the view), to_url fixing function name (with reverse lookup)

Url established under the project file

from app.conver import Conver

register_converter (Conver, 'YYYY') and using the register 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 content

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

Page display

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

 

Guess you like

Origin www.cnblogs.com/ljf520hj/p/11700505.html