创建项目
[code]
python manage.py startproject myporject
[/code]
运行服务器
Window下命令行切换到项目中manage.py 所在的文件路径下,输入:
[code]
python manage.py runserver
[/code]
用Ctrl + C关闭服务程序
创建应用
有了项目以后,就可以在它的下面创建应用(按照Django的说法是‘app’)了。我们再次用manage.py来创建这个blog app。
Window下命令行切换到项目中manage.py 所在的文件路径下,输入:
[code]
python manage.py startapp blog
[/code]
创建并同步数据库
用sqlite数据库
[code]python manage .py syncdb[/code]
当执行syncdb命令时,Django会查找INSTALLED_APPS 里面的每一个models.py文件,并为找到的每一个model都创建一张数据库表。
每次往项目里添加新的应用后,都要运行下syncdb命令,以确保它所需的表已经在数据库里面创建了。
模型
数据模型通常是web应用程序的基础。
Django的数据库模型层大量使用了ORM(对象关系映射)
变量类型:
CharField和TextField,前者是定长的,而后者的长度几乎无限。
EmailField、URLField和IPAddressField,其实是CharField加了一些验证而已。
BooleanField和NullBooleanField ,前者用于存储True或False,后者可
以存储Null。
FileField 是最复杂的变量之一。
AutoField 自增
模型之间的关系:
外键:models.ForeignKey(模型类)
多对多:models.ManyToManyField()
模型之间可以继承
|———-抽象基础类
|———-多表继承
Meta嵌套类
告知Django关于这个模型的各种元数据信息
查询语法:
查询由模式生成的数据库需要使用两个不同但却相似的类:
Manger和QuerySet,每个模型类都会展示一个objects属性,它构成了
这个模型在数据库中的所有查询。Manger是从数据库中获取信息的门户。
模板(在views文件中使用此方法)
使用模板对象的三种方式
[code lang=”python”]
from django.shortcuts import render
from django.template import loader,Context,Template #template is a package
from django.http import HttpResponse
from django.shortcuts import render_to_response
# Create your views here.
def index(req):
t = loader.get_template(‘<h1>{{uname}}</h1>’) ##这里的字符串必须是html片段,而不能是文件名。
c = Context({‘uname’:’alen,use loader.get_template() method.’})
html = t.render(c) #it’s type is str
return HttpResponse(html)
def index01(req):
t = Template(‘index.html’)
c = Context({‘uname’:’index01 use class Template.’})
html = t.render(c) #it’s type is str
return HttpResponse(html)
def index02(req):
return render_to_response(‘index.html’,{‘uname’:’use render_to_response method’})
[/code]
URL映射机制,请求响应对象
Http建模
HttpRequest对象
所有的视图函数都接收一个“请求”参数HttpRequest对象,它是一组经过良好的封装的属性代表了从web服务器传进来的原始的HTTP请求。
GET和POST字典
包含COOKIE和session的成员变量,查看API
HttpResponse对象
中间件
请求中间件,响应中间件
视图与逻辑
模板
Linux 命令行下python manage.py shell
可以进入命令行解释器。首先保证安装了ipython至于没有安装ipython的机器我不知道会有什么后果。但是ipython下竟然会有提示。
引用Django的model层的对象,Employee
Sqlite3
Linux 首先保证Linux上安装了sqlite3 ,
代开或者新建sq文件,sqlite3 文件名.db
.tables 显示数据库中所有的表
.schema tablename 显示创建表的SQL语句
select * from table_name; 查询表中所有的数据
.headers ON 当查询显示数据库信息时,打开表头
格式化输出:.head ON 回车
.mode column