django版本区别

django1.X与2.X、3.X

1.区别

urls.py中的路由匹配方法

  • 1.X第一个参数正则表达式
    url()
  • 2.X和3.X第一个参数不支持正则表达式,写什么就匹配什么 re_path
    path()
  • 如果想要使用正则,那么2.X与3.X也有响应的方法
    from django.urls import path,re_path
    re_path 等价于 1.X里面的url方法

2.转换器

五种常用转换器(Path converters)
str,匹配除了路径分隔符(/)之外的非空字符串,这是默认的形式
int,匹配正整数,包含0。
slug,匹配字母、数字以及横杠、下划线组成的字符串。
uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。
path,匹配任何非空字符串,包含了路径分隔符(/)(不能用?)

自定义

regex 类属性,字符串类型

to_python(self, value) 方法,value是由类属性 regex 所匹配到的字符串,返回具体的Python变量值,以供Django传递到对应的视图函数中。

to_url(self, value) 方法,和 to_python 相反,value是一个具体的Python变量值,返回其字符串,通常用于url反向引用。

自定义转换器示例:

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位

posted @ 2022-03-08 14:55  寻月隐君  阅读(87)  评论(0编辑  收藏  举报