URL配置(URLconf)就像Django 所支撑网站的目录。它的本质是URL与要为该URL调用的视图函数之间的映射表。
from django.conf.urls import url urlpatterns = [ url(正则表达式, views视图函数,参数,别名), ]
注意:Django 2.0版本中的路由系统已经替换成下面的写法:
from django.urls import path 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), ]
位置参数:
from django.conf.urls import url from . import views urlpatterns = [ url(r‘^articles/2003/$‘, views.special_case_2003), url(r‘^articles/([0-9]{4})/$‘, views.year_archive), url(r‘^articles/([0-9]{4})/([0-9]{2})/$‘, views.month_archive), url(r‘^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$‘, views.article_detail), ]
# 是否开启URL访问地址后面不为/跳转至带有/的路径的配置项 APPEND_SLASH=True
Django settings.py配置文件中默认没有 APPEND_SLASH 这个参数,但 Django 默认这个参数为 APPEND_SLASH = True。 其作用就是自动在网址结尾加‘/‘。
例子:
from django.conf.urls import url from app01 import views urlpatterns = [ url(r‘^blog/$‘, views.blog), ]
访问 http://www.example.com/blog 时,默认将网址自动转换为 http://www.example/com/blog/ 。
如果在settings.py中设置了 APPEND_SLASH=False,此时我们再请求 http://www.example.com/blog 时就会提示找不到页面。
上面的示例使用简单的正则表达式分组匹配(通过圆括号)来捕获URL中的值并以位置参数形式传递给视图。
在更高级的用法中,可以使用分组命名匹配的正则表达式组来捕获URL中的值并以关键字参数形式传递给视图。
在Python的正则表达式中,分组命名正则表达式组的语法是(?P<name>pattern)
,其中name
是组的名称,pattern
是要匹配的模式。
下面是以上URLconf 使用命名组的重写(关键字参数):
from django.conf.urls import url from . import views urlpatterns = [ url(r‘^articles/2003/$‘, views.special_case_2003), url(r‘^articles/(?P<year>[0-9]{4})/$‘, views.year_archive), url(r‘^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$‘, views.month_archive), url(r‘^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$‘, views.article_detail), ]
相当于按以下方式调用视图函数:
views.month_archive(request, year="2017", month="12")
URLconf 在请求的URL 上查找,将它当做一个普通的Python 字符串。不包括GET和POST参数以及域名。
例如,http://www.example.com/myapp/ 请求中,URLconf 将查找myapp/。
在http://www.example.com/myapp/?page=3 请求中,URLconf 仍将查找myapp/
。
URLconf 不检查请求的方法。换句话讲,所有的请求方法 —— 同一个URL的POST
、GET
、HEAD
等等 —— 都将路由到相同的函数。
注意:捕获的参数永远都是字符串。
# urls.py中 from django.conf.urls import url from . import views urlpatterns = [ url(r‘^blog/$‘, views.page), url(r‘^blog/page(?P<num>[0-9]+)/$‘, views.page), ] # views.py中,可以为num指定默认值 def page(request, num="1"): pass
在上面的例子中,两个URL模式指向相同的view - views.page - 但是第一个模式并没有从URL中捕获任何东西。
如果第一个模式匹配上了,page()函数将使用其默认参数num=“1”,如果第二个模式匹配,page()将使用正则表达式捕获到的num值。
#At any point, your urlpatterns can “include” other URLconf modules. This #essentially “roots” a set of URLs below other ones. #For example, here’s an excerpt of the URLconf for the Django website itself. #It includes a number of other URLconfs: from django.conf.urls import include, url urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^blog/‘, include(‘blog.urls‘)), # 可以包含其他的URLconfs文件 ]
原文:https://www.cnblogs.com/xingye-mdd/p/9492696.html