python django 模板语言循环字典
urls.py
from django.conf.urls import url from django.contrib import admin from cmdb import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', views.index), ]
1.正则表达式一类对应统一页面 url(r'^index-(\d+)/', views.index),如果正则表达式有两个值((\d+)-(\d+)),那么在接受的时候也要有两个值def index(request,nid,vid):
2.url(r'^index-(?p<nid>\d+)-(?p<vid>\d+).html', views.index) 带有?p<nid>在接受的时候可以不分位置来写,按照这里给相应变量赋值。
3.使用第二种方式时,如果参数比较多 在接受的时候可以使用*args **kwargs
views.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render #from django.shortcuts import redirect USER_DICT={ 'k1':'root1', 'k2':'root2', 'k3':'root3', 'k4':'root4', 'k5':'root5', } def index(request): return render(request,'index.html',{'user_dict':USER_DICT})
def index(request,nid):
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{user_dict.k1}} <ul> {% for k,row in user_dict.items %} <li>{{k}}-{{row}}</li> {% endfor %} </ul> </body> </html>
对URL路由关系进行命名,以后可以根据此名称生成自己想要的URL
url(r'^asdfasdfdf/',views.index,name='indexx')
url(r'^asdfasdfdf/(\d+)/(\d+)/',views.index,name='index')
url(r'^buy/(?P<pid>\d+)/(?P<nid>\d+)/',views.index,name='i3')
url1=reverse('i1') #asdfasdfdf/
url1=reverse('i2',args=(1,2)) #yug/1/2/
url1=reverse('i3',kwargs={'pid':1,'nid':9}) #buy/1/9/
模板语言:
action={% url "indexx" %}
action={% url "indexx" 3 6 %}
action={% url "i3" pid=1 nid=9 %} #buy/1/9/
request.path_info #当前的URL
通过include() 进行路由分发:
urls.py 先 url(r'^monitor/',include('app02.urls'))
再app02文件夹内的urls文件中设置跳转的路径。