这么多天才看完Django的hello world示例,实在是惭愧至极。提高效率方面,看来还需要多多思考和调整啊 。
总结一下:
1. 创建一个project,一个能独立运行的site=ear/war?
2. 创建一个app,模块。(这种开发模式挺好的)
3. manage来管理一些基本的操作:运行,数据库操作
4. 站点的配置setting.py=web.xml
5. URL Mapping——urls.py,直接映射到了方法。
6. 基于模板的分离(使用Django来merge模型跟视图)
目前只是简单的了解了DJango的运行模式,具体的好处还需进一步深入,应该是提供了很多额外的功能,让开发者处理起request和response更加快捷吧。
python&django倡议更简洁的代码style
重新整理一下基本步骤 :
1. 创建project
django-admin.py startproject mysite
生成了四个文件:
__init__.py
manage.py——提供了网站的一些管理功能,启动服务器,生成app,访问数据库等。
settings.py——配置数据库,配置安装的应用(APP)及其它。
urls.py——URL映射,可以分模块的映射,保存在urlpatterns{}里面
2.运行服务器
manage.py runserver
3.设置数据库
在settings.py中DATABASES的配置。因为机子上没有别的数据库 , 于是使用了其默认安装的Sqlite 。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'D:/prictise/mysite/hello.db', # Or path to database file if using sqlite3.
'USER': 'tod', # Not used with sqlite3.
'PASSWORD': 'tod', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
4.将需要创建数据库或表创建好
manage.py syncdb
syncdb的意思是将缓存或程序handle住但没写入数据库的内容写入数据库。
基本的数据和site配置好了,开始添加模块 :
5.创建app
manage.py startapp hello
在mysite下生成hello文件夹, 包含四个文件
__init__.py
models.py——就放置app相关的model了
tests.py——site测试代码位置
views.py——view的一些代码,运行时由urls.py映射过来,这点看起来跟struts2有点像,不过所有的MVC差不多都是这个德行的。
6.创建models
修改models.py文件,相当于Hibernate的bean,设置好属性字段及外键。
from django.db import models
import datetime
class Poll(models.Model) :
question = models.CharField(max_length=200) #字段
pub_date = models.DateTimeField('date_published') #字段
def __unicode__(self): #这个方法比较重要,类似于__str()__吧,Django里的写法?
return self.question
def thedate(self): #不是用在跟数据库相关的地方的
return "--" + self.question
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
was_published_today.short_description = 'Published today?'
class Choice(models.Model):
poll = models.ForeignKey(Poll) #外键的写法
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice
添加了两个entity
7.将app加入系统中
settings.py中的INSTALLED_APPS属性
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'hello',
'django.contrib.admin'
# Uncomment the next line to enable the admin:
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
8.在数据库中创建表
manage.py sql hello
显示结果——即会执行的语句 :
BEGIN;
CREATE TABLE "hello_poll" (
"id" integer NOT NULL PRIMARY KEY,
"question" varchar(200) NOT NULL,
"pub_date" datetime NOT NULL
)
;
CREATE TABLE "hello_choice" (
"id" integer NOT NULL PRIMARY KEY,
"poll_id" integer NOT NULL REFERENCES "hello_poll" ("id"),
"choice" varchar(200) NOT NULL,
"votes" integer NOT NULL
)
;
COMMIT;
9.这才真正的创建了表,上面只是看看语句
manage.py syncdb
10.可以自由的查看创建的model,以及通过接口来保存或修改数据
>>> from hello.models import Poll, Choice # Import the model classes we just wrote.
# No polls are in the system yet.
>>> Poll.objects.all()
[]
# Create a new Poll.
>>> import datetime
>>> p = Poll(question="What's up?", pub_date=datetime.datetime.now())
# Save the object into the database. You have to call save() explicitly.
>>> p.save()
# Now it has an ID. Note that this might say "1L" instead of "1", depending
# on which database you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
>>> p.id
1
# Access database columns via Python attributes.
>>> p.question
"What's up?"
>>> p.pub_date
datetime.datetime(2007, 7, 15, 12, 00, 53)
# Change values by changing the attributes, then calling save().
>>> p.pub_date = datetime.datetime(2007, 4, 1, 0, 0)
>>> p.save()
# objects.all() displays all the polls in the database.
>>> Poll.objects.all()
直接在命令行里操作数据,这点不错,比JAVA ORM直观多了
11. 配置urls.py,把admin的注释去掉
urlpatterns = patterns('',
# Example:
# (r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
)
12.开启admin site
创建superuser
manage.py createsuperuser --username=tod --email=tod@example.com
13.将model设置成admin可控制:在hello中创建一个admin.py文件,添加以下内容
from hello.models import *
from django.contrib import admin
admin.site.register(Poll)
admin.site.register(Choice)
即把两个entity注册到admin模块上
14.重启
15.用admin.ModelAdmin来配置管理页面
class PollAdmin(admin.ModelAdmin):
fieldsets = [ (None,{'fields': ['question']}),
('Date information', {'fields': ['pub_date']}),
]
admin.site.register(Poll, PollAdmin)
或者用类似方法来修改页面的显示。
16. 进一步,我们通过配置来添加自己的页面,urls.py中添加这些映射。
(r'^hello/$', 'hello.views.index'),
(r'^hello/(?P<poll_id>\d+)/$', 'hello.views.detail'),
(r'^hello/(?P<poll_id>\d+)/results/$', 'hello.views.results'),
(r'^hello/(?P<poll_id>\d+)/vote/$', 'hello.views.vote'),
17. 为hello/views 添加映射文件中配置的方法
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the poll index.")
def detail(request, poll_id):
return HttpResponse("You're looking at poll %s." % poll_id)
def results(request, poll_id):
return HttpResponse("You're looking at the results of poll %s." % poll_id)
def vote(request, poll_id):
return HttpResponse("You're voting on poll %s." % poll_id)
方法也都很简单,显示而已。
18.跟其他MVC框架一样,使用模块来作页面逻辑分离(在17上作的修改)
from django.template import Context, loader
from hello.models import Poll
from django.http import HttpResponse
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
t = loader.get_template('hello/index.html')
c = Context({
'latest_poll_list': latest_poll_list,
})
return HttpResponse(t.render(c))
def detail(request, poll_id):
return HttpResponse("You're looking at poll %s." % poll_id)
def results(request, poll_id):
return HttpResponse("You're looking at the results of poll %s." % poll_id)
def vote(request, poll_id):
return HttpResponse("You're voting on poll %s." % poll_id)
19.当然 还缺一个模板,在mysite\template文件夹下的hello/index.html
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li><a href="/hello/{{ poll.id }}/">{{ poll.question }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
20.页面的一些改进
# -*- coding: cp936 -*-
更紧凑的写法
return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
或返回404错误
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/detail.html', {'poll': p})
http://djangobook.py3k.cn