首页 > 程序开发 > Web开发 > Python >

Django项目4

2013-01-07

准备工作[plain] django-admin startproject web04 django-admin startapp blog 把blog注册到setting.py python manage.py runserver 配置url[python] from django.conf.urls.defaults import pa...

准备工作
[plain]
django-admin startproject web04
django-admin startapp blog
把blog注册到setting.py
python manage.py runserver
配置url
[python]
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
url(r'^blog/index/$','blog.views.index')
)
配置views
[python]
#coding:utf8
from django.http import HttpResponse
from django.template import loader,Context
def index(req):
t=loader.get_template('index.html')
name = 'dragon'
passwd = 'redhat'
admin = True
books = ['python','java','ruby']
emps = [ #处理列表的例子
['a',21,'m'],
['b',22,'f'],
['c',23,'m'],
]
empo = { #处理字典的例子
'name1':'dragon',
'age1':22,
'sex1':'male',
}
empp = [ #处理列表字典嵌套
{'name':'alln','age':23},
{'name':'alen','age':23},
{'name':'all','age':23},
{'name':'alle','age':23},
{'name':'llen','age':23},
{'name':'aen','age':23},
]
c=Context({
'name':name,'admin1':admin,
'books':books,'empo':empo,
'empp':empp,'emps':emps,
'passwd':passwd})
return HttpResponse(t.render(c))
这次的重头戏,配置模板标签!
[html]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>
{ %if admin1 and passwd == &#39;redhat&#39; %}
<h2>welcome admin {{name}}</h2>
{ %else% }
<h2>welcome normal {{name}}</h2>
{ %endif% }
<hr />
{%for i in books%}
{{forloop.counter}}
{%if i == &#39;python&#39;%}
<li style="color:red">{{i}}</li>
{%else%}
<li>{{i}}</li>
{%endif%}
{%endfor%}
<hr />
{% for emp in emps %}
<li style="color:blue">
{%for i in emp%}
{{i}}
{%endfor%}
</li>
{%endfor%}
<hr />
{% for k,v in empo.items %}
<li>
{{k}} {{v}}
</li>
{%endfor%}
<hr />
{% for emp in empp %}
<li style="color:green">
{% for k,v in emp.items %} <!--emp.items()把字典转化为了数组-->
{{k}} {{v}}
{%endfor%}
</li>
{%endfor%}
</body>
</html>
相关文章
最新文章
热点推荐