当前位置:主页 > 软件编程 > Python代码 >

Django Path转换器自定义及正则代码实例

时间:2021-03-30 09:09:30 | 栏目:Python代码 | 点击:

Django默认Path转换器

​step1 . 在urls.py 的同级目录下,创建converters.py

class Year_Converters():
  regex = '\d{4}'
  def to_python(self,value):
    return int(value)

  def to_url(self,value):
    # return ;04d' % value
    return str(value)

step 2 注册converters 在同级urls,py 文件

from django.urls import path,register_converter
from . import views
from . import converters

 #注册转换器
 register_converter(converters.Year_Converters,'year')
 urlpatterns = [
  path('show1/<year:arg>', views.show1),
]

正则 在urls,py 文件中,注意参数需要加() ,这里的参数是元组

from django.urls import re_path
urlpatterns = [
  re_path('article/(\d+)/', views.index),
]

正则关键字

re_path(r'^show3/(?P<id>\d{4})/', views.show3)

您可能感兴趣的文章:

相关文章