django学习(一)
一、安装django
1、下载django:http://www.djangoproject.com/download/(我安装的版本:Django-1.0.2-final)
2、解压后在在命令行执行 python setup.py install,安装过程中会将文件copy到 D:\Python25\Lib\site-packages下。
3、修改path环境变量,追加D:\Python25\Scripts。
4、验证是否安装成功,随便找一个文件夹在命令行执行django-admin.py startproject leesite,如果成功创建文件夹sitename,django安装成功!
leesite下有四个文件:
__init__.py
- 表示这是一个 Python 的包
- manage.py
- 提供简单化的 django-admin.py 命令,特别是可以自动进行 DJANGO_SETTINGS_MODULES 和 PYTHONPATH 的处理,而没有这个命令,处理上面环境变量是件麻烦的事情
- settings.py
- 它是django的配置文件
- uls.py
- url映射处理文件, Karrigell 没有这种机制,它通过目录/文件/方法来自动对应,而 Django 的url映射是url对于某个模块方法的映射,目前不能自动完成
注意点:
1》django-admin.py,请注意不是下划线。
二、Hello django!
1、启动webserver
启动:E:\liyp\django\leesite>manage.py runserver
浏览:http://localhost:8000/,Welcome to Django!
2、在E:\liyp\django\leesite>下新建一个helloworld.py文件。
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, Django.")
3、修改urls.py
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^leesite/', include('leesite.foo.urls')),
(r'^$', 'leesite.helloworld.index'),
# 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/(.*)', admin.site.root),
)
三、实现一个加法功能
1、在E:\liyp\django\leesite>下新建一个add.py文件。
from django.http import HttpResponse
text="""<form method="post" action="/add/">
<input type="text" name="a" value="%d">
+
<input type="text" name="b" value="%d">
<input type="submit" value="=">
<input type="text" value="%d">
</form>"""
def index(request):
if request.POST.has_key('a'):
a=int(request.POST['a'])
b=int(request.POST['b'])
else:
a=0
b=0
return HttpResponse(text%(a,b,a+b))
3、修改urls.py
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^leesite/', include('leesite.foo.urls')),
(r'^$', 'leesite.helloworld.index'),
(r'^add/$','leesite.add.index'),
# 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/(.*)', admin.site.root),
)
注意点:
1、 action 为 /add/,在 Django 中链接后面一般都要有 '/' ,不然有可能得不到 POST 数据。
2、 method="post",表示要对数据进行修改,GET 表示获取数据。
3、浏览http://localhost:8000/add/查看效果。
四、使用模板
1、创建list.py
#coding=utf-8
from django.shortcuts import render_to_response
address = [
{'name':'张三', 'address':'地址一'},
{'name':'李四', 'address':'地址二'}
]
def index(request):
return render_to_response('list.html', {'address': address})
注意:
1、使用汉字时采用utf-8编码。
2、address为一个list,每个list为一个字典。
2、创建模板
1、新建模板文件夹:E:\liyp\django\leesite\templates
2、设置模板路径:修改settings.py
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'./templates',
)
3、建立模板文件 E:\liyp\django\leesite\templates\list.html
<h2>通讯录</h2>
<table border="1">
<tr><th>姓名</th><th>地址</th></tr>
{% for user in address %}
<tr>
<td>{{ user.name }}</td>
<td>{{ user.address }}</td>
</tr>
{% endfor %}
</table>
注意:
1、文件格式为utf-8
4、修改访问路径 urls.py(http://localhost:8000/list/)
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^leesite/', include('leesite.foo.urls')),
(r'^$', 'leesite.helloworld.index'),
(r'^add/$','leesite.add.index'),
(r'^list/$','leesite.list.index'),
# 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/(.*)', admin.site.root),
)
五、生成并下载CSV格式文件
1、创建csv_test.py
#coding=utf-8
from django.http import HttpResponse
from django.template import loader, Context
address = [
('张三', '地址一'),
('李四', '地址二')
]
def output(request, filename):
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s.csv' % filename
t = loader.get_template('csv.html')
c = Context({
'data': address,
})
response.write(t.render(c))
return response
2、添加模板 E:\liyp\django\leesite\templates\csv.html
{% for row in data %}"{{ row.0|addslashes}}", "{{ row.1|addslashes}}",
{% endfor %}
3、修改urls.py(http://localhost:8000/csv/address)
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^leesite/', include('leesite.foo.urls')),
(r'^$', 'leesite.helloworld.index'),
(r'^add/$','leesite.add.index'),
(r'^list/$','leesite.list.index'),
(r'^csv/(?P<filename>\w+)/$', 'leesite.csv_test.output'),
# 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/(.*)', admin.site.root),
)
六、session
1、创建logon.py
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
def login(request):
username = request.POST.get('username', None)
if username:
request.session['username'] = username
username = request.session.get('username', None)
if username:
return render_to_response('login.html', {'username':username})
else:
return render_to_response('login.html')
def logout(request):
try:
del request.session['username']
except KeyError:
pass
return HttpResponseRedirect("/login/")
2、创建模板 E:\liyp\django\leesite\templates\login.html
{% if not username %}
<form method="post" action="/login/">
用户名:<input type="text" name="username" value=""><br/>
<input type="submit" value="登录">
</form>
{% else %}
你已经登录了!{{ username }}<br/>
<form method="post" action="/logout/">
<input type="submit" value="注销">
</form>
{% endif %}
3、修改urls.py(http://localhost:8000/login)
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^leesite/', include('leesite.foo.urls')),
(r'^$', 'leesite.helloworld.index'),
(r'^add/$','leesite.add.index'),
(r'^list/$','leesite.list.index'),
(r'^csv/(?P<filename>\w+)/$', 'leesite.csv_test.output'),
(r'^login/$', 'leesite.login.login'),
(r'^logout/$', 'leesite.login.logout'),
# 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/(.*)', admin.site.root),
)
4、配置数据库 django中的session是保存在数据库中的,在settings.py中设置数据库
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = './data.db'
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
sqlite是一个轻量级的数据库,类似于Access,但是没有像Access一样提供丰富的界面组件。从python 2.5开始,python提供了对sqlite3的内生支持,
在PythonDir\Dlls\下可以看到
sqlite3.dll和_sqlite3.pyd
,这2个文件是python支持sqlite3的基础;
5、建库、建表
manage.py syncdb
在E:\liyp\django\leesite下会多出一个data.db文件。
参考:
http://www.woodpecker.org.cn/obp/django/django-stepbystep/newtest/doc/