About
RSS

Bit Focus


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

Posted at 2010-02-03 14:09:53 | Updated at 2024-04-19 16:39:31

上节回顾 – 配置 基本视图和逻辑

数据库配置

    仍然在 settings.py 中, 找到 DATABASE_ 开头的项目. 现在用 sqlite3 作为数据库, 它已经集成在 python 2.5 以后的版本中, 这样就省去了安装配置的环节. 现在修改这些项目
DATABASE_ENGINE = 'django.db.backends.sqlite3'
DATABASE_NAME = 'guestbook/db_file'
这里 DATABASE_NAME 同样需要给出文件的绝对路径, 原理跟之前模板目录那个一样, 如果不能确定每次的工作目录, 那么就填绝对 db_file 的路径吧. 保存设置, 然后执行数据库同步操作
$ guestbook/manage.py syncdb
会输出提示
Creating table auth_permission
Creating table auth_group
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no):
这些是 django 为内置的用户, 会话等类型建立的表, 最后询问是否立即建立一个超级用户. 这里答 yes (仅一个 y 是不行的唉), 然后输入用户名, 电子邮箱和密码. 最后会建立表的索引, 然后结束. 现在, 你可以在 guestbook 目录下看到文件 db_file 了, 它是数据库使用的文件.

ORM 和数据库操作

    django 的 ORM 非常轻松. 打开 home 目录下的 models.py, 建立留言类型
from django.db import models

class Message(models.Model):
    name = models.CharField(max_length=32)
    content = models.CharField(max_length=32)
    dt = models.DateTimeField(auto_now=True)
注, 使用 django 的 ORM, 该类型需要继承于 models.Model, 而要往数据库中放的数据项, 需要是 models 模块中的对应的域类型. 至于 auto_now=True, 它指出时间和日期在该对象插入数据库时自动使用当前日期时间.
    类型弄好了, 得再同步一次数据库. 这些操作可以不重启服务器
$ guestbook/manage.py sql home
$ guestbook/manage.py syncdb
    回到 guestbook/home/views.py, 增加函数 save_message, 让它将表单数据存入数据库, 并重定向回到首页
from django.shortcuts import render_to_response
from guestbook.home.models import Message
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

def save_message(req):
    msg = Message()
    msg.name = req.GET['name']  if 'name' in  req.GET else ''
    msg.content = req.GET['content'] if 'content' in req.GET else ''
    msg.save()
    return HttpResponseRedirect(reverse('guestbook.home.views.display'))
save 操作将对象存入数据库, 很方便. HttpResponseRedirect 进行重定向, 而 reverse 函数将模块名, 也就是其参数字符串 ‘guestbook.home.views.display’, 逆映射到 URL, 也就是 http://localhost:8000/ 避免在 urls.py 之外的地方去硬编码 URL 地址.
    修改 guestbook/urls.py 为 save_message 添加 URL 映射.
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'),
    (r'^save/$', 'guestbook.home.views.save_message'),
)
    同时修改 guestbook/views/echo.html 修改它提交数据的目标
<html>
<body>
<form action='/save' method='get'>
<input type='text' name='name'/><br>
<input type='text' name='content'/><br>
<input type='submit' value='提交' />
</form>
    这时首页功能已经不能用了. 我们将首页改改, 让它从数据库中取得留言并显示在页面上. 先修改模板页面 guestbook/views/home.html
<html>
<body>
{% if messages %}
  {% for msg in messages %}
    {% if msg.name %}
      <b>{{ msg.name }}</b>
    {% else %}
      <i>匿名人</i>
    {% endif %}

    在 {{ msg.dt|date:"D d M Y H:i:s" }}

    {% if msg.content %}
      写道 {{ msg.content }}
    {% else %}
      打了一瓶酱油就走了
    {% endif %}
    <br>
  {% endfor %}
{% endif %}
这个模板页面要求传入一个可迭代的 messages 集, 并显示每条消息. 下面是 display 函数的改动, 它从数据库中取得全部留言, 按时间降序排序后, 弄出其中的前 20 条传递给页面
def display(req):
    return render_to_response('home.html', {
                'messages': Message.objects.all().order_by('-dt')[:20],
            })
    结束了, 现在你的网站又活过来了.

下节看点 – 后台管理 静态文件

Post tags:   Web Server  Tutorial  Python  django  ORM

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