Django的URL路由

时间:2022-03-31 03:20:20

URL配置(URLconf)就像Django 所支撑网站的目录。它的本质是URL模式以及要为该URL模式调用的视图函数之间的映射表;你就是以这种方式告诉Django,对于这个URL调用这段代码,对于那个URL调用那段代码

URL模式

urlpatterns = [
url(正则表达式, view函数, 参数, 别名),
]

  

参数说明

  • 一个正则表达式字符串
  • 一个可调用对象,通常为一个视图函数或一个指定视图函数路径的字符串
  • 可选的要传递给视图函数的默认参数(字典形式)
  • 一个可选的name参数,接合模板方便管理

看看默认的URL的分发的文件

"""ORM URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin urlpatterns = [
url(r'^admin/', admin.site.urls),
]

  

正则表达式的最前面的r表示raw_string 原生字符串。

正则表达式的分组

正则表达的分组用()

无名分组

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), ]

  

有名分组

(?p<分组名>正则语法)

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),
] # View (in blog/views.py)
def page(request, num):
retrun HttpRespouse(num)

  

name别名

name就是该views函数的别名

name别名要结合模板文件来用方便管理

例如:

urls.py
urlpatterns = [
url(r"register",views.register,name="reg"),
] 在html文件中引入
<form action="{% url 'reg' %}" method="post">

  

路由转发器(include)

如果一个项目下有很多的app,那么在urls.py里面就要写巨多的urls映射关系。这样看起来很不灵活,而且杂乱无章。这时候就要根据不同的app来分发不同的url请求

首先,在urls.py里写入urls映射条目。注意要导入include方法

from django.conf.urls import include, url
from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls),
url(r'^app01/', include('app01.urls')),
]

  

这条关系的意思是将url为”app01/“的请求都交给app01下的urls去处理

其次,在app01下创建一个urls.py文件,用来处理请求的url,使之与views建立映射

from django.conf.urls import include, url
from app01 import views urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'index/$', views.index), ]