Django项目1
准备工作[plain]
django-admin.py startproject web02 【创建一个web02项目】
django-admin.py startapp blog 【创建一个应用名为blog】
然后在blog下面建立一个文件夹,templates,放置html模板。
python manage.py runserver 【启动django开发服务器】
去settings.py,把刚建立的应用注册进去。
[python]
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
)
先配置views.py 视图文件
[python]
#encoding:utf8
from django.http import HttpResponse
from django.template import loader,Context
class Person(object):
def __init__(self,name,age,易做图):
self.name = name
self.age = age
self.易做图 = 易做图
def say(self):
return self.name +' '+ str(self.age) +' '+self.易做图
def index(req):
t=loader.get_template('index.html')#加载模板文件
name='tom'
age=23
易做图='male'
title = 'emp'
marry = True
booklist=['python','php','java']
booktuple=('a','b','c')
books={'a':'python','b':'c++'}
zhangsan=Person('zhangsan',23,'male')
c=Context({ #加载文件里的内容
'name':name,
'age':age,
'易做图':易做图,
'title':title,
'marry':marry,
'booklist':booklist,
'booktuple':booktuple,
'books':books,
'zhangsan':zhangsan,
})
html=t.render(c) #用模板渲染内容
return HttpResponse(html) #返回渲染后的内容
def add(req): #前面index是描述重点,后面这三个是最简单的情况
return HttpResponse('add list')
def dele(req):
return HttpResponse('delete list')
def select(req):
return HttpResponse('select list')
再配置urls.py,配置好以后,这几个页面都可以访问了。
[python]
#coding:utf8
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
url(r'^blog/index/$','blog.views.index'), #前半如果匹配正则,后半就调用blog包中views模块的index方法
url(r'^blog/add/$','blog.views.add'),
url(r'^blog/dele/$','blog.views.dele'),
)
urlpatterns += patterns('blog.views', #此处可作为前缀,另外,patterns可叠加
url(r'^blog/select/$','select'),
)
这里以index为例,编辑templates文件夹下的index.html文件,重点渲染
[html]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>{{title}}</title>
</head>
<body>
<h1>name is:{{name}}<br /> <!-- 这里的{{双层花括号}}下面的值,在blog.views.index中,c=Context()里面,已经用字典的方式指定好了 -->
age is:{{age}}<br />
marry is:{{marry}}<br />
booklist is:{{booklist}}<br />
booktuple is:{{booktuple}}<br />
1.{{booktuple.0}}<br />
books is{{books}}<br />
2.{{books.a}}<br />
zhangsan:{{zhangsan}}<br />
3.{{zhangsan.name}}<br />
4.{{zhangsan.say}} <!-- 数组列表字典,类的属性和方法,都用点方法来表示 -->
</h1>
</body>
</html>
最后,去浏览器,输入网址,即可。
补充:Web开发 , Python ,