首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Django课程:第一个Django应用程序(1部分)

2013-09-26 
Django教程:第一个Django应用程序(1部分)Django教程:第一个Django应用程序(1部分) 2013-09-23 磁针石 #承

Django教程:第一个Django应用程序(1部分)

Django教程:第一个Django应用程序(1部分)

 

2013-09-23 磁针石

 

#承接软件自动化实施与培训等gtalk:ouyangchongwu#gmail.com qq 37391319

#博客:http://blog.csdn.net/oychw

#版权所有,转载刊登请来函联系

# 深圳测试自动化python项目接单群113938272深圳广州软件测试开发 6089740

#深圳湖南人业务户外群66250781武冈洞口城步新宁乡情群49494279

#参考资料:https://docs.djangoproject.com/en/1.5/intro/tutorial01/

# http://django-chinese-docs.readthedocs.org/en/latest/intro/tutorial01.html

 

请看实例。本教程中将创建一个基本的投票应用。

 

它由两部分组成:查看投票的结果和投票的公共网站;添加、修改和删除投票的管理站点。

请先确认Django已经安装并检查版本号:

# python -c "import django;print(django.get_version())"

1.5.1

本教程基于 Django 1.5.*和Python 2.x。

寻求帮助:django-users或#django onirc.freenode.net 

创建project

# django-admin.py startproject mysite

这将在当前目录创建 mysite 目录。注意需要避免使用 python 保留字或 Django组件名作为project名称。尤其注意不要使用如:django (与 Django 本身会冲突)或者 test (与 Python 内置的包名会冲突).

         Project创建的文件如下:

# ls -R mysite

mysite:

manage.py mysite

 

mysite/mysite:

__init__.py settings.py urls.py  wsgi.py

 

l 外层 mysite根目录是你project容器。对Django该目录名并不重要; 你可以重命名。

l manage.py: 可让你以各种方式与Django项目进行交互命令行工具。你可以在 django-admin.py和manage.py 中查看manage.py 更多信息。

l 内层 mysite目录是project的实际 Python 包。

l mysite/__init__.py: 包初始化文件,默认为空.

l mysite/settings.py: 配置文件。

l mysite/urls.py: project的 URL 声明。

l mysite/wsgi.py: 一个 WSGI 兼容的 Web 服务器的入口,以便运行你的项目。

 

开发服务器

         现在已经有一个简单的服务器了。进入外层mysite目录,执行

# python manage.py runserver

Validating models...

 

0 errors found

September 22, 2013 - 01:04:43

Django version 1.5.4, using settings'mysite.settings'

Development server is running athttp://127.0.0.1:8000/

Quit the server with CONTROL-C.

这样就启动了 Django开发服务器,一个纯Python的轻量级 Web 服务器。Django包含了它。这样在产品投入使用之前不必配置产品服务器例如 Apache,方便更加快速开发。

 

**不要** 在任何生产环境中使用此服务器。它仅适用于开发。(Django提供的是 Web 框架的,而不是 Web 服务器。)

 

服务器运行时,在你Web 浏览器中访问http://127.0.0.1:8000/ 。你会看到 “Welcome toDjango”页面,表明开发服务器工作正常。

 

默认runserver 命令启动的开发服务器只监听localIP 的 8000 端口。

改变端口:

python manage.py runserver 8080

改变IP ,需要和端口号一起传递。因此,要监听所有外部 IP 地址:

python manage.py runserver 0.0.0.0:8000

更多资料参见runserver 。

 

数据库设置

编辑 mysite/settings.py 。这是一个普通的 Python 模块,包含了Django 模块级变量的设置。更改 DATABASES 中 'default' 下的以下键的值,以匹配您的数据库连接设置。

 

l ENGINE –  'django.db.backends.postgresql_psycopg2'或'django.db.backends.mysql',或'django.db.backends.sqlite3', 'django.db.backends.oracle' , 更多的参见alsoavailable。

 

l NAME – 数据库名。对 SQLite,是绝对路径的文件名(好像project下面文件直接输入文件名就可以,因为在GAE,SAE等云平台,是不太可能知道真实路径的?);如果该文件不存在,它会在第一次同步数据库时自动创建(见下文)。

 

当指定路径时,总是使用斜杠,即使是Windows 下(例如:``C:/homes/user/mysite/sqlite3.db``) 。

 

l USER – 用户名 ( SQLite 下不需要) 。

l PASSWORD – 密码 ( SQLite 下不需要) 。

l HOST – 数据库主机地址。如果是同一台物理机器,请将此处保留为空 (或者设置为 127.0.0.1) ( SQLite 下不需要) 。查看HOST了解详细信息。

 

如果你是数据库新手,我们建议使用 SQLite ,将 ENGINE 改为 'django.db.backends.sqlite3' 并且将 NAME 设置为你想存放数据库的地方。 Python 内置了SQLite,不需要额外安装。

 

当你编辑 settings.py 时,将 TIME_ZONE 修改为你所在的时区。默认值是美国中央时区(芝加哥)。

中国一般设置为TIME_ZONE = 'Asia/Shanghai'。

 

同时,注意文件底部的 INSTALLED_APPS 设置。它保存了当前 Django 实例已激活的所有 Django 应用。每个应用可以被多个项目使用,而且你可以打包和分发给其他人。

 

默认情况下,:setting:INSTALLED_APPS 包含以下应用,这些都是由 Django 提供的:

 

l     django.contrib.auth – 身份验证系统。

l     django.contrib.contenttypes – 内容类型框架。

l     django.contrib.sessions – session 框架。

l     django.contrib.sites – 网站管理框架。

l     django.contrib.messages – 消息框架。

l     django.contrib.staticfiles – 静态文件管理框架。

 

所有这些应用中每个应用至少使用一个数据库表,所以在使用它们之前需要创建数据库中的表:

python manage.py syncdb

 

syncdb 命令参照 settings.py 文件中的INSTALLED_APPS 设置创建必要的数据库表。每创建一个数据库表你都会看到一条消息,接着你会看到一个提示询问你是否想为验证系统内创建个超级用户。我们选择需要。

 

数据库命令行下输入:``dt``(PostgreSQL), SHOW TABLES; (MySQL), 或 .schema (SQLite) 可列出 Django 所创建的表。

 

创建模型

Djaong每个应用都是由Python 包,这些在Python path 中并且遵循django命名规范。 Django 有工具可以自动生成应用的基本目录架构,你可以专注于编写代码而不是去创建目录。

项目 ( Projects ) vs. 应用 ( apps )

项目与应用之间有什么不同之处?应用是一个提供具体功能的 Web 应用– 例如:博客系统、公共记录的数据库或简单的投票系统。项目是特定的 Web 网站相关的配置和其应用的集合。一个项目可以包含多个应用。一个应用可以在多个项目中使用。

 

你的应用可以存放在 Python path 中的任何位置。在本教程中,通过你的 manage.py 文件创建投票应用,以便它可以作为顶层模块导入,而不是作为 mysite 的子模块。

 

要创建你的应用,请确认与 manage.py 文件在同一的目录下并输入以下命令:

 

python manage.py startapp polls

这将创建一个 polls 目录,其展开的样子如下所示::

 

polls/

   __init__.py

   models.py

   tests.py

   views.py

 

编写数据库支持的 Web 应用的第一步是定义模型– 从本质是数据库设计及其元数据。

模型是有关你数据的唯一且明确的数据源。它包含了你所要存储的数据的基本字段和行为。 Django 遵循DRY原则 。目标是为在一个地方定义你的数据模型就可从中自动获取数据。

 

在这简单的投票应用中,我们将创建两个模型: Poll 和 Choice``。``Poll 有问题和发布日期两个字段。``Choice`` 有两个字段:选项 ( choice ) 的文本内容和投票数。每一个 Choice 都与一个 Poll 关联。

 

这些概念都由简单的Python 类来表示。编辑 polls/models.py:

from django.db import models

 

class Poll(models.Model):

   question = models.CharField(max_length=200)

   pub_date = models.DateTimeField('date published')

 

class Choice(models.Model):

   poll = models.ForeignKey(Poll)

   choice_text = models.CharField(max_length=200)

   votes = models.IntegerField(default=0)

代码很简单。每个模型都由继承自 django.db.models.Model的类来描述。 每个模型都有一些类变量,每一个类变量都代表了一个数据库字段。

 

每个字段由一个 Field的实例来表现 – 比如 CharField 表示字符类型的字段和DateTimeField 表示日期时间型的字段。这会告诉 Django 每个字段都保存了什么类型的数据。

每个 Field 实例的名字就是字段的名字(如: question 或者 pub_date ),其格式接近机器语言。在你的 Python 的代码中会使用这个值,而你的数据库会将这个值作为列名。

 

初始化 Field 实例时第一个可选参数可以设立用户友好的名字。Django的内省会使用它,文档有更多的使用以提高可读性。若该字段未提供,Django 将使用机器语言。

 

一些 Field 类有必选参数, 例如 CharField 需要你指定max_length`。

 Field 实例可以有不同的可选参数; 在本例中,我们将votes 的 default 的值设为 0 。

 

最后,注意我们使用了ForeignKey 定义了一个关联。它告诉 Django 每一个``Choice`` 关联一个 Poll 。 Django 支持常见数据库的所有关联:多对一,多对多和一对一。

 

激活模型

模型代码提供给 Django 大量信息。Django 就可以做:

 

l 为应用创建数据库模式 (CREATE TABLE 语句) 。

l 创建 Python 访问Poll 和 Choice 对象的数据库API 。

首先需要在安装polls 应用。Django 应用是“可插拔的”:你可以在多个项目使用一个应用,你还可以发布应用,因为它们没有被捆绑到指定的 Django 安装。

再次编辑 settings.py 文件,在 INSTALLED_APPS 设置中加入 'polls' 字符。如下所示:

INSTALLED_APPS = (

   'django.contrib.auth',

   'django.contrib.contenttypes',

   'django.contrib.sessions',

   'django.contrib.sites',

   'django.contrib.messages',

   'django.contrib.staticfiles',

   # Uncomment the next line to enable the admin:

   # 'django.contrib.admin',

   # Uncomment the next line to enable admin documentation:

   # 'django.contrib.admindocs',

   'polls',

)

注意polss要有引号和逗号,现在 Django 已经知道包含了 polls 应用。让我们运行如下命令:

python manage.py sql polls

你将看到类似如下所示内容 ( 有关投票应用的 CREATE TABLE SQL 语句 ):

BEGIN;

CREATE TABLE "polls_poll" (

   "id" serial NOT NULL PRIMARY KEY,

   "question" varchar(200) NOT NULL,

   "pub_date" timestamp with time zone NOT NULL

);

CREATE TABLE "polls_choice" (

   "id" serial NOT NULL PRIMARY KEY,

   "poll_id" integer NOT NULL REFERENCES "polls_poll"("id") DEFERRABLE INITIALLY DEFERRED,

   "choice_text" varchar(200) NOT NULL,

   "votes" integer NOT NULL

);

COMMIT;

请注意:

 

l 具体的输出根据数据库会有所不同。

l 表名是自动生成,组合应用名 (polls) 和小写的模型名(poll 和 choice),可重载此行为。

l 主键 (IDs) 是自动添加的,可重载。

l 通常Django 会在外键字段名上附加 "_id" ,可重载。

l 外键由 REFERENCES 语句显示声明。

l SQL 语句时和数据库类型相关,会为你自动处理特定于数据库的字段,例如 auto_increment (MySQL), serial (PostgreSQL), 或 or integerprimary key (SQLite) 。上面输出的是 PostgreSQL 的语法。

l sql没有数据库中真正执行,仅仅显示SQL语句。

其他命令:

 

python manage.py validate – 检查在模型错误。

python manage.py sqlcustom polls – 输出应用自定义的SQL 语句 (?例如表修改或约束) 。

python manage.py sqlclear polls –如果表已经存在输出必要的DROP TABLE 。

python manage.py sqlindexes polls– 为应用输出 CREATEINDEX 语句。

python manage.py sqlall polls –等同于sql, sqlcustom,和 sqlindexes之和。

 

再次运行 syncdb 命令在数据库中创建这些模型对应的表:

 

python manage.py syncdb

 syncdb 命令会给没有数据库表的开启执行sqlall 操作。为上次执行 syncdb 命令以后的添加的应用创建表、初始化数据和索引。 syncdb 命令可以随时调用,它只会创建不存在的表。

 

了解 manage.py 工具更多的功能参见。

 

 

玩转API

 

Python 的交互式 shell 中也可以玩转 DjangoAPI 。执行:

python manage.py shell

manage.py 设置了DJANGO_SETTINGS_MODULE 环境变量,导入了mysite/settings.py中的相关设置。这是和直接敲python的区别。

 

>>> from polls.models importPoll, Choice   # Import themodel classes we just wrote.

 

# No polls are in the system yet.

>>> Poll.objects.all()

[]

 

# Create a new Poll.

# Support for time zones is enabled in thedefault settings file, so

# Django expects a datetime with tzinfofor pub_date. Use timezone.now()

# instead of datetime.datetime.now() andit will do the right thing.

>>> from django.utils importtimezone

>>> p = Poll(question="What'snew?", pub_date=timezone.now())

 

# Save the object into the database. Youhave to call save() explicitly.

>>> p.save()

 

# Now it has an ID. Note that this mightsay "1L" instead of "1", depending

# on which database you're using. That'sno biggie; it just means your

# database backend prefers to returnintegers as Python long integer

# objects.

>>> p.id

1

 

# Access database columns via Pythonattributes.

>>> p.question

"What's new?"

>>> p.pub_date

datetime.datetime(2012, 2, 26, 13, 0, 0,775217, tzinfo=<UTC>)

 

# Change values by changing theattributes, then calling save().

>>> p.question = "What'sup?"

>>> p.save()

 

# objects.all() displays all the polls inthe database.

>>> Poll.objects.all()

[<Poll: Poll object>]

``<Poll: Poll object>`` 的显示比较丑,且没有实际意义。 编辑 polls 模型( 在 polls/models.py 文件中 ) 并且给 Poll 和 Choice 都添加一个__unicode__() 方法:

 

class Poll(models.Model):

   # ...

   def __unicode__(self):  # Python3: def __str__(self):

       return self.question

 

class Choice(models.Model):

   # ...

   def __unicode__(self):  # Python3: def __str__(self):

       return self.choice_text

添加 __unicode__() 方法是相当重要的,不仅让你在命令行下有明确提示,而且在 Django 自动生成的管理界面中也有好的对象展示。

 

Django 模型默认处理的是Unicode 格式。所有数据库中的数据返回时都会转换为 Unicode。

Django 模型有个默认的__str__() 方法会调用 __unicode__() 并将结果转换为 UTF-8 编码的字符串。这就意味着 unicode(p) 会返回一个 Unicode 字符串,而 str(p) 会返回一个以 UTF-8 编码的普通字符串。

还可以添加自定义方法, 比如:

 

import datetime

from django.utils import timezone

# ...

class Poll(models.Model):

   # ...

   def was_published_recently(self):

       return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

时区相关的内容,参见time zone support docs

保存后重新执行python manage.py shell:

>>> from polls.models importPoll, Choice

 

# Make sure our __unicode__() additionworked.

>>> Poll.objects.all()

[<Poll: What's up?>]

 

# Django provides a rich database lookupAPI that's entirely driven by

# keyword arguments.

>>> Poll.objects.filter(id=1)

[<Poll: What's up?>]

>>>Poll.objects.filter(question__startswith='What')

[<Poll: What's up?>]

 

# Get the poll that was published thisyear.

>>> from django.utils importtimezone

>>> current_year =timezone.now().year

>>>Poll.objects.get(pub_date__year=current_year)

<Poll: What's up?>

 

# Request an ID that doesn't exist, thiswill raise an exception.

>>> Poll.objects.get(id=2)

Traceback (most recent call last):

   ...

DoesNotExist: Poll matching query does notexist. Lookup parameters were {'id': 2}

 

# Lookup by a primary key is the mostcommon case, so Django provides a

# shortcut for primary-key exact lookups.

# The following is identical toPoll.objects.get(id=1).

>>> Poll.objects.get(pk=1)

<Poll: What's up?>

 

# Make sure our custom method worked.

>>> p = Poll.objects.get(pk=1)

>>> p.was_published_recently()

True

 

# Give the Poll a couple of Choices. Thecreate call constructs a new

# Choice object, does the INSERTstatement, adds the choice to the set

# of available choices and returns the newChoice object. Django creates

# a set to hold the "other side"of a ForeignKey relation

# (e.g. a poll's choices) which can beaccessed via the API.

>>> p = Poll.objects.get(pk=1)

 

# Display any choices from the relatedobject set -- none so far.

>>> p.choice_set.all()

[]

 

# Create three choices.

>>>p.choice_set.create(choice_text='Not much', votes=0)

<Choice: Not much>

>>>p.choice_set.create(choice_text='The sky', votes=0)

<Choice: The sky>

>>> c =p.choice_set.create(choice_text='Just hacking again', votes=0)

 

# Choice objects have API access to theirrelated Poll objects.

>>> c.poll

<Poll: What's up?>

 

# And vice versa: Poll objects get accessto Choice objects.

>>> p.choice_set.all()

[<Choice: Not much>, <Choice: Thesky>, <Choice: Just hacking again>]

>>> p.choice_set.count()

3

 

# The API automatically followsrelationships as far as you need.

# Use double underscores to separaterelationships.

# This works as many levels deep as youwant; there's no limit.

# Find all Choices for any poll whosepub_date is in this year

# (reusing the 'current_year' variable wecreated above).

>>>Choice.objects.filter(poll__pub_date__year=current_year)

[<Choice: Not much>, <Choice: Thesky>, <Choice: Just hacking again>]

 

# Let's delete one of the choices. Usedelete() for that.

>>> c =p.choice_set.filter(choice_text__startswith='Just hacking')

>>> c.delete()

欲了解更多有关模型关系的信息,参见Accessing related objects. 。欲了解更多有关如何使用双下划线来通过 API 执行字段查询的,参见Field lookups。 如需完整的数据库 API 信息,参见Database API reference

热点排行