views:
from django.shortcuts import render,redirect from django.shortcuts import HttpResponse # Create your views here. from django.views import View class Home(View): def dispatch(self, request, *args, **kwargs): print('before') result = super(Home,self).dispatch(request,*args,**kwargs) print('after') return result def get(self,request): print('in get') return render(request,'home.html') def post(self,request): print('in post') return render(request,'home.html') user_dict = { 'k1':{'name':'hrg','email':'hrg@163.com','pwd':'123'}, 'k2':{'name':'eric','email':'hrg@163.com','pwd':'111'}, 'k3':{'name':'hhh','email':'hrg@163.com','pwd':'222'}, 'k4':{'name':'kkk','email':'hrg@163.com','pwd':'123'}, } def detail(request,uid,nid): v = "nid:"+nid+"uid:"+uid return render(request,'detail.html',{'user_dict':user_dict,})
templates:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> {% for k in user_dict.keys %} <li>{{ k }}</li> {% endfor %} </ul> <ul> {% for v in user_dict.values %} <li>{{ v }}</li> {% endfor %} </ul> <ul> {% for k,v in user_dict.items %} <li>{{ k }}:{{ v }}</li> {% endfor %} </ul> </body> </html>
在每一个for循环中,都有一forloop属性。
forloop.counter 当前循环的计数器顺排,用处大了,可以给循环打上序号
forloop.counter0 当前循环的计数器顺排,从0开始
forloop.revcounter forloop.revcounter0 跟上面一样是倒排
forloop.first forloop.last 是否是第一次循环或最后一次循环
{% for i in v1 %}
<tr><td>{{ forloop.counter }}</td></td></tr>
{% endfor %}
如果还有嵌套for,子for内还有 forloop.parentloop属性是一个包含上面6个属性的字典,其值如:
{'parentloop': {}, 'counter0': 0, 'counter': 1, 'revcounter': 3, 'revcounter0': 2, 'first': True, 'last': False}