Django的视图
不同于其他语言的MVC模式,Django采用的是MVT模式,即Model、View、Template,这里的View其实质就是其他语言中的Controller(emmm.....),而Template其实就是html文件,所以原理其实大同小异,这里就不多赘述
配置URL
Django中的默认路由在项目主目录下的urls.py中,基本路由配置如下所示:
from django.urls import path, include
from . import views
urlpatterns = [
path('articles/2003/', views.special_case_2003),
path('articles/<int:year>/', views.year_archive),
path('articles/<int:year>/<int:month>/', views.month_archive),
path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
path('', include('test.urls')) # 引入不同应用的url配置
]
以上为普通匹配方式,其中有几种能够限制路由中参数类型的函数可以使用。
- str: 匹配除路径分隔符'/'之外的任何非空字符串
- int:匹配零或任何正整数
- slug:匹配由ASCII字母或数字组成的任何slug字符串,以及连字符'-'和下划线'_'字符
- uuid:匹配格式化的UUID
- path:匹配任何非空字符串,包括路径分隔符 '/'
使用正则表达式匹配
from django.urls import path, re_path
from . import views
urlpatterns = [
path('articles/2003/', views.special_case_2003),
re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive), # ?P<year>意为指定参数的名字
re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<slug>[\w-]+)/$', views.article_detail),
]