About
RSS

Bit Focus


django 架设网站入门指南[零]

Posted at 2010-02-03 05:02:06 | Updated at 2024-04-26 00:58:38

安装

    根据 django 官方文档, 需要 python 2.3 或更高版本. 不过按现在的 python 普及程度, 想必大家的机器上都有 python 2.5 或 2.6 了. 我的操作系统是 ubuntu 9.10, 自带的是 2.6 版本.
    debian 用户安装 django 很简单, 只需要
# apt-get install python-django
就可以了, 其它发行版看有没有类似的方法. 或者在官方站点下载源代码安装
    祝好运.

建立项目 startproject

    首先找到一个地方, 建立一个项目 guestbook, 我们将在这个项目中搭建一个留言板.
$ django-admin startproject guestbook
有些系统中 django-admin 并非一个命令, 需要
$ python django-admin.py startproject guestbook
    执行完这个之后, 当前目录下会创建一个名为 guestbook 的目录, 里面包含了一个最简单的服务器: 显示一个主页. 执行
$ python guestbook/manage.py runserver
启动后会看到类似以下输出
Validating models...
0 errors found

Django version 1.1.1, using settings 'guestbook.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
这时, manage.py 已经在本地 8000 端口创建了一个服务器, 赶快打开浏览器去访问吧!

    为 guestbook/manage.py 加上可执行属性 (在 ubuntu 9.10 下该属性已经自动添加了)
$ chmod u+x guestbook/manage.py

创建应用 startapp

    在 django 世界的哲学里, 每个功能称之为一个应用. 创建应用也使用 manage.py 来完成. 比如现在用以下命令创建一个首页应用
$ guestbook/manage.py startapp home
这时 guestbook 目录下会多出一个 home 目录, 里面有这些文件
__init__.py
models.py
tests.py
views.py
    比较烦的是, 这时得回去修改设置, 打开 settings.py 查找 INSTALLED_APPS, 在这一坨里面加一行
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'guestbook.home',
)
    这样 home 应用才算是有了名分. 好, 现在再来实现功能. 因为现在只是处理页面, 所以只需要在 guestbook/home/views.py 里面修修补补就好了. 打开它, 其实相当于是个空文件, 把这一段代码放进去
from django.http import HttpResponse

def display(req):
    return HttpResponse('<html><body>hello, django!')
    我知道你已经不耐烦了, 如果你曾经写 php 的话. 不过现在还有最后一步, 修改路径映射. 打开 guestbook/urls.py, 在里面加一句话
urlpatterns = patterns('',
    # Example:
    # (r'^guestbook/', include('guestbook.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)),

    (r'^$', 'guestbook.home.views.display'),
)
小心, 后面那个是字符串, 重复一次, 是字符串. 它将由 django 框架进行反射, 而你不需要配置任何的服务器信息.
    现在再来访问 http://localhost:8000/ 出现的就是…
    PS: 无须重启服务器.

使用模板

    将 html 直接写在源代码里面是一件很怪的事情, 我们可是 python 程序员呢.
    解决的方法呢, 就是把 html 里面固定的部分写在 html 模板文件中, 然后在 python 逻辑中处理动态的部分. 废话少说, 现在开始. 首先打开 guestbook/settings.py, 找到 TEMPLATE_DIRS, 在注释丛中添加模板搜索目录
TEMPLATE_DIRS = (
    # Don't forget to use absolute paths, not relative paths.a
    'guestbook/views',
)
    呃, 上面注释说要绝对路径, 这个嘛, 因为模板搜索时, 工作路径是服务器启动时的路径. 刚才的例子中我们在和 guestbook 目录平级的目录下, 所以这里填写这个相对路径也行. 如果不确定自己是否每次都会从一样的地方启动服务器, 那么这里最好写上 views 目录的绝对路径.
    现在, 再潜入 views 目录, 建立模板文件 home.html, 内容
<html>
<body>
Hello, {{ message }}!
其中, {{ message }} 就是将在逻辑部分被动态替换的变量.
    最后, 重写视图逻辑. 修改 guestbook/home/views.py
from django.shortcuts import render_to_response

def display(req):
    return render_to_response('home.html', {
                    'message': 'django template'
                })
render_to_response 第一个参数是模板文件名, 第二个参数是一个映射, 将模板中的变量 message 映射为字符串 django template.
    现在刷新页面吧.

处理表单

    上面 display 函数的第一个参数, 也就是 http 请求, 它包含了页面请求信息. 这个参数使不能省的.
    接下来在 views 目录下创建一个 echo.html 文件, 由它向服务器提交请求
<html>
<body>
<form action='/' method='get'>
<input type='text' name='name'/><br>
<input type='text' name='content'/><br>
<input type='submit' value='提交' />
</form>
然后修改 home.html 扩充它的动态部分来显示 name 和 content
<html>
<body>
{{ name }} 刚才说到: {{ content }}
然后修改 guestbook/urls.py, 加上 echo 的份
urlpatterns = patterns('',
    # Example:
    # (r'^guestbook/', include('guestbook.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)),

    (r'^$', 'guestbook.home.views.display'),
    (r'^echo/$', 'guestbook.home.views.echo'),
)
最后是 guestbook/home/views.py, display 函数改改, 再增加 echo 的处理
def display(req):
    return render_to_response('home.html', {
              'name': req.GET['name'] if 'name' in  req.GET else '',
              'content': req.GET['content'] if 'content' in req.GET else '',
            })

def echo(req):
    return render_to_response('echo.html', {})
    现在转到 http://localhost:8000/echo 随便输入点什么, 然后提交, 就会…
    PS: 因为 echo.html 中表单提交用的是 get 方法, 所以处理时使用的是 req.GET 成员; 如果用 post 方法, 则对应于 req.POST.

下节看点 – ORM 与数据库

Post tags:   Web Server  Tutorial  django  Python

Leave a comment:




Creative Commons License Your comment will be licensed under
CC-NC-ND 3.0


. Back to Bit Focus
NijiPress - Copyright (C) Neuron Teckid @ Bit Focus
About this site