1.URL路径中的特定部分数据
from django import http
from django.views import views
class Url_Parameters(View):
def get(self, request, num):
return http.HttpResponse("接收到URL路径中特定部分数据:%s" % num)
from django.urls import path, re_path
from . import views
urlpatterns = [
path('url_params/<int:num>/', views.Url_Prameters.as_view()),
]
---接收到URL路径中特定部分数据:18---
---总结:这个需求由<int:num>这个默认路由转换器接收URL特定部分的参数接收并赋值给num。---
DEFAULT_CONVERTERS = {
'int': IntConverter(),
'path': PathConverter(),
'slug': SlugConverter(),
'str': StringConverter(),
'uuid': UUIDConverter(),
}
疑问:默认路由转换器中没有用来匹配"手机号(11位数)"的路由转换器,怎么实现。
class ConvertersMobile():
regex = '1[3-9]\d{9}
def to_python(self, value):
return int(value)
def to_url(self, values):
return str(value)
from django.contrib import admin
from django.urls import path, include, register_converter
from converters import MobileConverter
register_converter(ConvertersMobile, 'mobile')
from django import http
from django.views import View
class UrlParamsPhoneNum(View):
def get(self, request, phone_num):
return http.HttpResposne('接收到的手机号是:', phone_num)
from django.urls import path, re_path
from . import views
urlpatterns = [
path('test_params/<mobile:phone_num>/', views.UrlParamsPhoneNum.as_view()),
]
---获取到的结果---
接收到的手机号是:18838883888