Python自动化之django URL
URL
url(r'^detail-(?P<nid>\d+)-(?P<uid>\d+).html', views.detail)
会把(?P
\d+)和(?P \d+)传到后台
需要在函数添加参数
def detail(request, *args,**kwargs):
pass
第一种写法:url(r'^detail-(\d+)-(\d+).html', views.detail)
def func(request, nid, uid):
pass
def func(request, *args):
args = (2,9)
def func(request, *args, **kwargs):
args = (2,9)
(\d+)会传到*args里面
第二种写法:url(r'^detail-(?P<nid>\d+)-(?P<uid>\d+).html', views.detail)
def func(request, nid, uid):
pass
def funct(request, **kwargs):
kwargs = {'nid': 1, 'uid': 3}
(?P
\d+)会传到**kwargs
name自定义URL名称
对URL路由关系进行命名, ***** 以后可以根据此名称生成自己想要的URL *****
url(r'^asdfasdfasdf/', views.index, name='i1'),
url(r'^yug/(\d+)/(\d+)/', views.index, name='i2'),
url(r'^buy/(?P<pid>\d+)/(?P<nid>\d+)/', views.index, name='i3'),
这个那么name参数到底有什么作用呢?
{% url "i1" %} # asdfasdfasdf/
{% url "i2" 1 2 %} # yug/1/2/
{% url "i3" pid=1 nid=9 %} # buy/1/9/
当你urls.py里面的地址进行修改之后,只有模板里面写的是name的值,模板文件不用改,都会随着URL的改变而改变,省了很多事。
reverse函数
def func(request, *args, **kwargs):
from django.urls import reverse
url1 = reverse('i1') # asdfasdfasdf/
url2 = reverse('i2', args=(1,2,)) # yug/1/2/
url3 = reverse('i3', kwargs={'pid': 1, "nid": 9}) # buy/1/9/
反转,什么是反转?
就是把URL地址所对应的“views函数”或者是“URL对应的name参数”逆向解析成URL地址
示例1:通过views函数反解析出URL:
模板文件
<a href="{% url 'news.views.year_archive' 2012 %}">2012 Archive</a>
{# Or with the year in a template context variable: #}
<ul>
{% for yearvar in year_list %}
<li><a href="{% url 'news.views.year_archive' yearvar %}">{{ yearvar }} Archive</a></li>
{% endfor %}
</ul>
解析函数
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
def redirect_to_year(request):
# ...
year = 2006
# ...
return HttpResponseRedirect(reverse('news.views.year_archive', args=(year,)))
示例2:通过name反解析出URL:
模板文件
url(r'^asdfasdfasdf/', views.index, name='i1'),
url(r'^yug/(\d+)/(\d+)/', views.index, name='i2'),
url(r'^buy/(?P<pid>\d+)/(?P<nid>\d+)/', views.index, name='i3'),
解析函数
def func(request, *args, **kwargs):
from django.urls import reverse
url1 = reverse('i1') # asdfasdfasdf/
url2 = reverse('i2', args=(1,2,)) # yug/1/2/
url3 = reverse('i3', kwargs={'pid': 1, "nid": 9}) # buy/1/9/
当前URL
request.path_info
多级路由
项目目录
project/urls.py
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^cmdb/', include("app01.urls")),
url(r'^monitor/', include("app02.urls")),
]
APP目录
app01/urls.py
from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^login/', views.login),
]
app02/urls.py
from django.conf.urls import url,include
from django.contrib import admin
from app02 import views
urlpatterns = [
url(r'^login/', views.login),
]
感谢关注