标签:articles 匹配 差异 detail Django 版本 article path hello
Django版本差异
url和path
Django1.x路由层使用的是url方法
Django2.x和Django3.x版本中路由层使用的是path方法
url()第一个参数支持正则
path() 第一个参数是不支持正则,写什么就匹配什么。
2.x和3.x还支持re_path,相当于1.x中的url,第一个参数支持正则,不过不推荐
path中的转换器
虽然path不支持正则,但是他的内部支持五种转换器
str,匹配除了路径分隔符(/)之外的非空字符串,这是默认的形式 int,匹配正整数,包含0。 slug,匹配字母、数字以及横杠、下划线组成的字符串。 uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。 path,匹配任何非空字符串,包含了路径分隔符(/)(不能用?)
例子
path('articles/<int:year>/<int:month>/<slug:other>/', views.article_detail) # 针对路径http://127.0.0.1:8000/articles/2009/123/hello/,path会匹配出参数year=2009,month=123,other='hello'传递给函数article_detail
自定义转换器
除了有默认的五个转换器之外,还支持自定义转换器
1、在app01下新建文件path_ converters.py,文件名可以随意命名
class MonthConverter: regex='\d{2}' # 属性名必须为regex def to_python(self, value): return int(value) def to_url(self, value): return value # 匹配的regex是两个数字,返回的结果也必须是两个数字
2、在urls.py中,使用register_converter
将其注册到URL配置中:
from django.urls import path,register_converter from app01.path_converts import MonthConverter register_converter(MonthConverter,'mon') from app01 import views urlpatterns = [ path('articles/<int:year>/<mon:month>/<slug:other>/', views.article_detail, name='aaa'), ]
3、views.py中的视图函数article_detail
from django.shortcuts import render,HttpResponse,reverse def article_detail(request,year,month,other): print(year,type(year)) print(month,type(month)) print(other,type(other)) print(reverse('xxx',args=(1988,12,'hello'))) # 反向解析结果/articles/1988/12/hello/ return HttpResponse('xxxx')
4、测试
# 1、在浏览器输入http://127.0.0.1:8000/articles/2009/12/hello/,path会成功匹配出参数year=2009,month=12,other='hello'传递给函数article_detail # 2、在浏览器输入http://127.0.0.1:8000/articles/2009/123/hello/,path会匹配失败,因为我们自定义的转换器mon只匹配两位数字,而对应位置的123超过了2位
模型层里面1.x外键默认都是级联更新删除的,但是到了2.x和3.x中需要你自己动手配置参数
END
标签:articles,匹配,差异,detail,Django,版本,article,path,hello 来源: https://www.cnblogs.com/Snailsys/p/15956472.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。