DAY73-Django框架(四)

一、路由的简单配置

urlpatterns = [
#url(正则表达式,视图函数,参数,别名)
    url(r'^index/$', index,name='index'),
]

二、无名分组

分组之后,会将()里的数据以位置参数的形式,传给视图函数,视图函数就需要定义形参或以*args接受

url(r'^delauthor/(d+)(.html)$',delauthor,name='delauthor')

三、有名分组

分组之后,会将()里的数据以关键字参数的形式,传给视图函数,视图函数就需要定义形参或以**kwargs接受

有名分组的格式 (?P<组名>匹配的正则)

url(r'^delauthor/(?P<id>d+)(?P<html>.html)$',,delauthor,name='delauthor'),

注:有名分组和无名分组最好不要一同使用

四、反向解析

为了更方便的获取URL的最终形式,采用了别名和参数的形式灵活获取URL

无参数

#1.URL设置
url(r'^index/$', index,name='index'),
#2.在视图层
url=reverse('index')
#3.在模板层
{% url 'index' %}

无名分组

#1.URL设置
url(r'^delauthor/(d+)(.html)$',delauthor,name='delauthor'),
#2.在视图层
url=reverse('delauthor')
#3.在模板层
{% url 'delauthor' author.id '.html' %}

有名分组

#1.URL设置
url(r'^delauthor/(?P<id>d+)(?P<html>.html)$', delauthor,name='delauthor'),
#2.在视图层
url=reverse('delauthor',args=(author.id '.html'))
#3.在模板层
{% url 'delauthor' author.id '.html' %}

五、路由分发

由于一个项目不只有一个app,所以URL会有很多,到时候一个urls.py文件会显得很混乱。所以在每个app里添加一个urls.py来存放当前app的URL,而总的urls.py存放所有的urls.py

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

#注:总路由,不能加结束符$
    

六、名称空间

由于name没有作用域,Django在反解URL时,会在项目全局顺序搜索,当查找到第一个name指定URL时,立即返回。所以当两个在不同app下的URL的name重复时,会产生冲突

为了解决这一问题,有两种方法

#方法一,在分发路由时,分配名称空间
url(r'^app01/', include('app01.urls',spacename='app01')),
#使用
app01:路由别名

    
#方法二,在设置路由别名时,加上前缀,不要重复
url(r'^delauthor/(d+)(.html)$',delauthor,name='app01_delauthor')
url(r'^delauthor/(d+)(.html)$',delauthor,name='app02_delauthor')

七、伪静态

在配置路由时,在末尾加上.html,将该路径伪装成html文件,让使用者以为是静态文件

#路由:
	url(r'^book/(?P<id>d+.html)',views.book),
#访问:
	http://127.0.0.1:8000/book/4.html
原文地址:https://www.cnblogs.com/xvchengqi/p/9923421.html