Django Path转换器自定义及正则代码实例
作者:--TINGXIN-- 时间:2022-05-19 09:01:25
Django默认Path转换器
str:匹配任何非空字符串,但不含斜杠/,如果你没有专门指定转换器,那么这个是默认使用的;
int:匹配0和正整数,返回一个int类型
slug:可理解为注释、后缀、附属等概念,是url拖在最后的一部分解释性字符。该转换器匹配任何ASCII字符以及连接符和下划线,比如' building-your-1st-django-site‘;
uuid:匹配一个uuid格式的对象。为了防止冲突,规定必须使用破折号,所有字母必须小写,例如'075194d3-6885-417e-a8a8-6c931e272f00‘ 。返回一个UUID对象;
path:匹配任何非空字符串,重点是可以包含路径分隔符'/‘。这个转换器可以帮助你匹配整个url而不是一段一段的url字符串
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)
来源:https://www.cnblogs.com/tingxin/p/12932259.html
标签:Django,Path,转换器,自定义,正则
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Django返回HTML文件的实现方法
2022-12-25 16:26:16
![](https://img.aspxhome.com/file/2023/8/79458_0s.png)
python处理Excel xlrd的简单使用
2023-11-29 04:13:32
SQL server使用自定义函数以及游标
2011-11-03 17:26:27
python取代netcat过程分析
2021-07-22 17:32:51
python matplotlib库的基本使用
2023-07-20 11:22:45
![](https://img.aspxhome.com/file/2023/5/97255_0s.jpg)
python读写文件操作示例程序
2021-04-03 13:09:49
Jupyter加载文件的实现方法
2021-11-12 23:16:15
![](https://img.aspxhome.com/file/2023/8/85058_0s.jpg)
np.ones的使用小结
2021-05-20 06:55:34
![](https://img.aspxhome.com/file/2023/7/101327_0s.png)
python在非root权限下的安装方法
2023-12-05 20:28:35
电子商务搜索LIST页面用户体验设计
2010-08-03 12:57:00
![](https://img.aspxhome.com/file/UploadPic/20108/3/20108313022804s.jpg)
python使用matplotlib绘制柱状图教程
2021-01-29 20:20:00
![](https://img.aspxhome.com/file/2023/5/118595_0s.png)
python实现电子书翻页小程序
2022-11-16 11:10:29
![](https://img.aspxhome.com/file/2023/3/117283_0s.png)
通过python实现windows桌面截图代码实例
2023-11-19 03:46:27
python中几种自动微分库解析
2022-12-20 18:24:02
asp的系统变量ServerVariables (“HTTP_USER_AGENT“)问题
2009-02-04 15:51:00
PHP autoload使用方法及步骤详解
2023-08-22 13:05:44
Python中列表与元组的乘法操作示例
2021-05-09 17:11:25
Python 面向对象编程的三大特性之继承
2021-08-18 18:19:04
![](https://img.aspxhome.com/file/2023/2/79412_0s.png)
Django debug为True时,css加载失败的解决方案
2022-05-07 01:17:53
pandas.DataFrame的for循环迭代的实现
2023-07-07 22:10:28