Django1.5官方入门教程第1部分

上传人:沈*** 文档编号:141502936 上传时间:2022-08-24 格式:DOC 页数:28 大小:225KB
收藏 版权申诉 举报 下载
Django1.5官方入门教程第1部分_第1页
第1页 / 共28页
Django1.5官方入门教程第1部分_第2页
第2页 / 共28页
Django1.5官方入门教程第1部分_第3页
第3页 / 共28页
资源描述:

《Django1.5官方入门教程第1部分》由会员分享,可在线阅读,更多相关《Django1.5官方入门教程第1部分(28页珍藏版)》请在装配图网上搜索。

1、第一个Django app, 第1部分让我们从例子开始学习.Throughout this tutorial, well walk you through the creation of a basic poll application.通过整个教程,我们会从头至尾向你介绍怎样创建一个基本的投票程序。Itll consist of two parts:这个应用程序这将包括两部分: A public site that lets people view polls and vote in them.一个能够让用户查看投票选项并进行投票的前台 An admin site that lets you

2、 add, change and delete polls.一个能够进行投票管理的后台Well assume you haveDjango installedalready. You can tell Django is installed and which version by running the following command:我们假设你已经安装了Django。通过下面的命令,你可以得到Django的版本。(译者注:Windows操作系统,首先将python的安装路径添加到系统路径中,然后在cmd中运行这个命令。)python -c import django; print(dj

3、ango.get_version()You should see either the version of your Django installation or an error telling “No module named django”. Check also that the version number matches the version of this tutorial. If they dont match, you can refer to the tutorial for your version of Django or update Django to the

4、newest version.你应该看Django版本号,或者是一条错误信息“django模块没有定义”。 请确定你的版本号与本教程的一致。 如果不一致,查看相应版本的教程,或把Django更新到本版本。SeeHow to install Djangofor advice on how to remove older versions of Django and install a newer one.请参阅如何卸载和安装Django。Where to get help:If youre having trouble going through this tutorial, please po

5、st a message todjango-usersor drop by#django on to chat with other Django users who might be able to help.Creating a project创建项目If this is your first time using Django, youll have to take care of some initial setup. Namely, youll need to auto-generate some code that establishes a Djangoproject a col

6、lection of settings for an instance of Django, including database configuration, Django-specific options and application-specific settings.如果这是你第一次使用Django,你需要注意一下初始化设置。也就是说,你需要自动创建一些Django项目初始化的代码包括数据库设置、Django特性设置以及程序特性设置。From the command line,cdinto a directory where youd like to store your code,

7、 then run the following command:在命令行界面下,进入到你放置代码的目录中,执行命令django-admin.pystartprojectmysite。django-admin.py startproject mysiteThis will create amysitedirectory in your current directory. If it didnt work, seeProblems running django-admin.py.这将在当前目录下创建一个mysite目录,如果失败,请查看有关运行django-admin.py的内容。NoteYou

8、ll need to avoid naming projects after built-in Python or Django components. In particular, this means you should avoid using names likedjango(which will conflict with Django itself) ortest(which conflicts with a built-in Python package).注意:你要避免用Python内置模块或是Django组件来命名项目。这就是说你应该避免使用django(与Django名称冲

9、突)或是test(与Python内置包冲突)这样的名称。Where should this code live?代码应该放在哪?If your background is in plain old PHP (with no use of modern frameworks), youre probably used to putting code under the Web servers document root (in a place such as/var/www). With Django, you dont do that. Its not a good idea to put a

10、ny of this Python code within your Web servers document root, because it risks the possibility that people may be able to view your code over the Web. Thats not good for security.Put your code in some directoryoutsideof the document root, such as/home/mycode.如果你有PHP的背景,你很可能习惯把代码放在Web服务器的文档根目录下面(比如/v

11、ar/www)。使用Django,你不用这么做。把Python代码放在Web服务器的文档根目录下面并不是一个好办法,因为这会增加用户通过Web服务器浏览你的代码的风险。 这样对系统安全性不好。把你的代码放在文档根目录之外,比如/home/mycode。Lets look at whatstartprojectcreated:我们来看看startproject都创建了些什么mysite/ manage.py mysite/ _init_.py settings.py urls.py wsgi.pyDoesnt match what you see?和你创建的不一样?The default pro

12、ject layout recently changed. If youre seeing a “flat” layout (with no innermysite/directory), youre probably using a version of Django that doesnt match this tutorial version. Youll want to either switch to the older tutorial or the newer Django version.我们最近修改了默认的项目布局。如果你没有看到内部的mysite目录,可能是因为你使用的Dj

13、ango版本和本教程不同。把你的Django更换为本教程的版本,或查看相关版本的教程。这些文件是: The outermysite/directory is just a container for your project. Its name doesnt matter to Django; you can rename it to anything you like.外部mysite目录仅仅是用来保存项目的。它的名字随意。 manage.py: A command-line utility that lets you interact with this Django project in

14、 various ways. You can read all the details aboutmanage.pyindjango-admin.py and manage.py.manage.py:命令交互行工具,可以让您以各种方式与该Django项目进行交互。 你可以在django-admin.pyandmanage.py找到与manage.py有关的所有细节资料。 The innermysite/directory is the actual Python package for your project. Its name is the Python package name youl

15、l need to use to import anything inside it (e.g.importmysite.settings).内部mysite目录实际上一个Python package,mysite就是package的名字。当你引用任何内容时,使用这个名字。如:import mysite.settings mysite/_init_.py: An empty file that tells Python that this directory should be considered a Python package. (Readmore about packagesin th

16、e official Python docs if youre a Python beginner.)一个空文件,用于告诉Python这个目录是一个Python package。 mysite/settings.py: Settings/configuration for this Django project.Django settingswill tell you all about how settings work.Django项目的配置文件。 mysite/urls.py: The URL declarations for this Django project; a “table

17、of contents” of your Django-powered site. You can read more about URLs inURL dispatcher.Django项目的URL声明。 mysite/wsgi.py: An entry-point for WSGI-compatible webservers to serve your project. SeeHow to deploy with WSGIfor more details.wsgi.py文件:项目的WSGI兼容Web服务器。The development server开发版服务器Lets verify th

18、is worked. Change into the outermysitedirectory, if you havent already, and run the commandpythonmanage.pyrunserver. Youll see the following output on the command line:看看是否能正常运行。进入外部的mysite目录,运行命令python manage.py runserver,你将会看到如下输出:Validating models.0 errors foundFebruary 28, 2013 - 15:50:53Django

19、version 1.5, using settings mysite.settingsDevelopment server is running at http:/127.0.0.1:8000/Quit the server with CONTROL-C.Youve started the Django development server, a lightweight Web server written purely in Python. Weve included this with Django so you can develop things rapidly, without ha

20、ving to deal with configuring a production server such as Apache until youre ready for production.Django开发版服务器,是一个使用Python编写的轻量级的服务器。它集成在Django中,在产品发布之前,以便你迅速开发。Nows a good time to note:Dontuse this server in anything resembling a production environment. Its intended only for use while developing. (

21、Were in the business of making Web frameworks, not Web servers.)注意:不要使用这个服务器部署项目,它只适合用于开发。Now that the servers running, visithttp:/127.0.0.1:8000/with your Web browser. Youll see a “Welcome to Django” page, in pleasant, light-blue pastel. It worked!确保服务器运行,然后在浏览器其中输入http:/127.0.0.1:8000/。你将看到Django的

22、欢迎页面。非常好,一切正常。修改端口By default, therunservercommand starts the development server on the at port 8000.默认情况下,runserver命令在内部IP的8000端口启动开发版服务器。If you want to change the servers port, pass it as a command-line argument. For instance, this command starts the server on port 8080:如果想要更改服务器端口,请把端口作为一个参数。例如,这个

23、命令将启动8080端口:python manage.py runserver 8080If you want to change the servers IP, pass it along with the port. So to listen on all public IPs (useful if you want to show off your work on other computers), use:如果你想改变IP,请把IP和端口一同作为参数。使用下面的用法,可以是服务被所有的公共IP访问:python manage.py runserver 0.0.0.0:8000Full d

24、ocs for the development server can be found in therunserverreference.开发版服务器的完整文档可以在这里找到。Database setup数据库设置Now, editmysite/settings.py. Its a normal Python module with module-level variables representing Django settings. Change the following keys in theDATABASESdefaultitem to match your database con

25、nection settings.编辑mysite/settings.py,这是一个普通的Python模块,包含很多代表Django设置的模块变量。修改DATABASES中的这些设置,用于配置你的数据库。 ENGINE Eitherdjango.db.backends.postgresql_psycopg2,django.db.backends.mysql,django.db.backends.sqlite3ordjango.db.backends.oracle. Other backends arealsoavailable.ENGINE的值,是django.db.backends.post

26、gresql_psycopg2, django.db.backends.mysql, django.db.backends.sqlite3 或 django.db.backends.oracle中的某一个。或类似django.db.backensd.XXX NAME The name of your database. If youre using SQLite, the database will be a file on your computer; in that case,NAMEshould be the full absolute path, including filename,

27、 of that file. If the file doesnt exist, it will automatically be created when you synchronize the database for the first time (see below).数据库的名字。如果你使用SQLite,数据库就是一个文件, 在这种情况下,Name应该是包括文件名的绝对路径。如果文件不存在,在第一次同步数据库时,它会被自动创建(见下文)。When specifying the path, always use forward slashes, even on Windows (e.g

28、.C:/homes/user/mysite/sqlite3.db).指定路径时,使用正斜杠,即使在Windows中。例如:C:/homes/user/mysite/sqlite3.db USER Your database username (not used for SQLite).数据库的用户名(SQLite不适用) PASSWORD Your database password (not used for SQLite).数据库的密码(SQLite不适用) HOST The host your database is on. Leave this as an empty string (

29、or possibly127.0.0.1) if your database server is on the same physical machine (not used for SQLite). SeeHOSTfor details.数据库所在主机。如果数据库服务器和应用程序在同一台物理主机上,可留空( 或127.0.0.1)(SQLite不适用)。请参阅HOST。If youre new to databases, we recommend simply using SQLite by settingENGINEtodjango.db.backends.sqlite3andNAMEto

30、 the place where youd like to store the database. SQLite is included in Python, so you wont need to install anything else to support your database.如果你不熟悉数据库,我们建议使用SQLite。设置ENGINE的值为django.db.backends.sqlite3 ,NAME的值可以是任意路径。SQLite集成在Python中,所以你不需要安装其他任何东西。注意If youre using PostgreSQL or MySQL, make su

31、re youve created a database by this point. Do that with “CREATEDATABASEdatabase_name;” within your databases interactive prompt.如果你使用PostgreSQL或MySQL,确保你已经创建了一个数据库。 在你的数据库的命令行中, 使用“CREATE DATABASE database_name“即可。If youre using SQLite, you dont need to create anything beforehand - the database file

32、 will be created automatically when it is needed.如果使用的是SQLite,不需要提前创建。在需要的时候,数据库文件会被自动创建。While youre editingsettings.py, setTIME_ZONEto your time zone. The default value is the Central time zone in the U.S. (Chicago).当你编辑settings.py文件时,把TIME_ZONE设置为你的时区。默认为美国芝加哥。Also, note theINSTALLED_APPSsetting t

33、oward the bottom of the file. That holds the names of all Django applications that are activated in this Django instance. Apps can be used in multiple projects, and you can package and distribute them for use by others in their projects.在编辑settings.py时,注意一下文件底部的INSTALLED_APPS设置。这个变量保存了在当前Django项目中可用

34、的Django程序的名称。Django程序可以在多个项目中复用,而且你可以把这些程序打包部署以供其他的程序调用By default,INSTALLED_APPScontains the following apps, all of which come with Django:默认情况下,INSTALLED_APPS包括以下应用程序,他们都是Django自带的。 django.contrib.auth-An authentication system认证系统 django.contrib.contenttypes-A framework for content types内容类型框架 djan

35、go.contrib.sessions-A session frameworkSession框架 django.contrib.sites A framework for managing multiple sites with one Django installation.管理一个项目中的多个站点的框架 django.contrib.messages A messaging framework.消息框架 django.contrib.staticfiles A framework for managing static files.静态文件管理框架These applications ar

36、e included by default as a convenience for the common case.为了方便公用,这些程序都默认包含在配置文件中Each of these applications makes use of at least one database table, though, so we need to create the tables in the database before we can use them. To do that, run the following command:每个程序都至少用到了一个数据表,所以,我们要在数据库中创建对应的

37、数据表。执行下面的命令python manage.py syncdbThesyncdbcommand looks at theINSTALLED_APPSsetting and creates any necessary database tables according to the database settings in yoursettings.pyfile. Youll see a message for each database table it creates, and youll get a prompt asking you if youd like to create a

38、 superuser account for the authentication system. Go ahead and do that.syncdb命令会查找INSTALLED_APPS设置并根据settings.py文件的数据库设置创建所有必须的数据表。每创建一个数据表的时候你都能看到对应的提示信息,并且系统还会提示你是否为认证系统创建一个超级用户。请按照提示创建超级用户。If youre interested, run the command-line client for your database and typedt(PostgreSQL),SHOWTABLES;(MySQL)

39、, or.schema(SQLite) to display the tables Django created.如果你感兴趣,可以进入到数据库命令行内,输入dt(PostgreSQL)、SHOWTABLES;(MySQL)或者.schema(SQLite)来显示Django创建的数据表。For the minimalists为最低要求者所准备Like we said above, the default applications are included for the common case, but not everybody needs them. If you dont need a

40、ny or all of them, feel free to comment-out or delete the appropriate line(s) fromINSTALLED_APPSbefore runningsyncdb. Thesyncdbcommand will only create tables for apps inINSTALLED_APPS.上面说道,默认的程序是为了方便共用包含进来的,但是不是所有人都需要它们。如果你一个都不需要,就在执行syncdb前将INSTALLED_APPS内的这些程序注释掉或者直接删除。syncdb只会为INSTALLED_APPS内的程序

41、创建数据表Creating models 创建模型Now that your environment a “project” is set up, youre set to start doing work.现在你的项目环境就已经建立好,可以开始正式的工作了。Each application you write in Django consists of a Python package, somewhere on yourPython path, that follows a certain convention. Django comes with a utility that autom

42、atically generates the basic directory structure of an app, so you can focus on writing code rather than creating directories.你用Django写成的每个程序都是由Python包组成的,这些包位于PythonPath中并遵循一定的命名规范。Django有个工具能够自动生成程序的基本目录结构,所以你可以专注与写代码而不用去创建目录app VS project项目 VS 程序Whats the difference between a project and an app?

43、An app is a Web application that does something e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects.项目(project)和程序(app)之间有什么不同?

44、程序是可以是一个博客系统、公共记录的数据库或非常简单的投票程序。项目是一个网站的配置和程序的集合。项目可以包含多个程序;程序也可以运用到多个项目中去。Your apps can live anywhere on yourPython path. In this tutorial, well create our poll app right next to yourmanage.pyfile so that it can be imported as its own top-level module, rather than a submodule ofmysite.你的apps可以放在Pyt

45、hon path中的任何地方。在本教程中,我们将把投票app创建在manage.py所在的路径中,这样,它就可以作为top-level模块被导入,而不是作为mysite的子模块。To create your app, make sure youre in the same directory asmanage.pyand type this command:要创建程序,请确定你现在位于manage.py的路径中,并输入以下命令python manage.py startapp pollsThatll create a directorypolls, which is laid out like

46、 this:这样做会创建一个polls目录,结构如下所示polls/ _init_.py models.py tests.py views.pyThis directory structure will house the poll application.这个目录就是投票程序的正式结构The first step in writing a database Web app in Django is to define your models essentially, your database layout, with additional metadata.在Django中开发一个有数据库

47、的Web程序的第一步就是定义模型就是数据库设计以及附加的元数据。Philosophy 原理A model is the single, definitive source of data about your data. It contains the essential fields and behaviors of the data youre storing. Django follows theDRY Principle. The goal is to define your data model in one place and automatically derive things

48、 from it.模型是你的数据的单一的、限定的源。它包含你要保存的数据的基本字段和行为。Django遵循DRY原则。目标是为了只在一处地方定义你的数据模型并能够自动从其中获取数据。In our simple poll app, well create two models:PollandChoice. APollhas a question and a publication date. AChoicehas two fields: the text of the choice and a vote tally. EachChoiceis associated with aPoll.在我们的

49、投票程序中,要创建两个模型:polls(投票)和choices(选项)。投票有问题和发布日期两个字段。选项有两个字段:每个选项的文本内容和投票统计。每个选项都和投票进行关联。These concepts are represented by simple Python classes. Edit thepolls/models.pyfile so it looks like this:这些概念都由Python类所表现出来。编辑polls/models.py文件,加入下面的代码from django.db import modelsclass Poll(models.Model): questi

50、on = 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)The code is straightforward. Each model is represented by a class that

51、subclassesdjango.db.models.Model. Each model has a number of class variables, each of which represents a database field in the model.上面的代码很直接。每个模型都由一个继承自django.db.models.Model的类来描述,都有一定数量的类变量,每个类变量都对应一个数据库字段Each field is represented by an instance of aFieldclass e.g.,CharFieldfor character fields an

52、dDateTimeFieldfor datetimes. This tells Django what type of data each field holds.每个字段都由一个Field类的实例来进行描述比如CharField表示字符类型的字段而DateTimeField表示日期时间型的。这会告诉Django数据库字段保存了什么类型的数据。The name of eachFieldinstance (e.g.questionorpub_date) is the fields name, in machine-friendly format. Youll use this value in

53、your Python code, and your database will use it as the column name.每个Field实例的名字(例如question或pub_date)就是字段的名字,字段的格式是亲和机器式的。在你的Python代码中会用到这个值,而数据库会将这个值认作表的列名。You can use an optional first positional argument to aFieldto designate a human-readable name. Thats used in a couple of introspective parts of

54、Django, and it doubles as documentation. If this field isnt provided, Django will use the machine-readable name. In this example, weve only defined a human-readable name forPoll.pub_date. For all other fields in this model, the fields machine-readable name will suffice as its human-readable name.你可以

55、在初始化Field实例时使用第一位置可选参数来指定一个符合人类习惯的名称。这在Django的一些内省部分中被使用到了,而且这个还能作为文档来增强代码的可读性。如果没有提供这个参数,Django会使用符合机器习惯的名称。例如,我们只为Poll.pub_date定义了一个人类名称。对于模型中的其他字段,机器名称就已经足够让人们理解它表示什么含义了SomeFieldclasses have required arguments.CharField, for example, requires that you give it amax_length. Thats used not only in t

56、he database schema, but in validation, as well soon see.有些Field类有必要元素。比如CharField,要求你指定max_length。这并不只是用于数据库里,我们以后就会看到它也用在数据验证中AFieldcan also have various optional arguments; in this case, weve set thedefaultvalue ofvotesto 0.一个Filed有各种可选参数,在这里,我们设置了votes的default参数为0。Finally, note a relationship is

57、defined, usingForeignKey. That tells Django eachChoiceis related to a singlePoll. Django supports all the common database relationships: many-to-ones, many-to-manys and one-to-ones.后,注意我们使用ForeignKey定义了一个关系。这会告诉Django每个Choice会同一个Poll进行关联。Django支持所有的通用数据库关系类型:多对一、多对多、一对一Activating models激活模型That smal

58、l bit of model code gives Django a lot of information. With it, Django is able to:刚才的一小段有关模型的代码,向Django提供了很多信息。 有了这些代码,Djangon能够: Create a database schema (CREATETABLEstatements) for this app.为程序创建对应的数据表。 Create a Python database-access API for accessingPollandChoiceobjects.给Poll和Choice对象创建数据库访问API。

59、But first we need to tell our project that thepollsapp is installed.但是首先我们需要告诉项目,投票程序已经安装就绪。Philosophy哲理Django apps are “pluggable”: You can use an app in multiple projects, and you can distribute apps, because they dont have to be tied to a given Django installation.Django程序是“插入式的”:你可以在多个项目中使用一个程序,

60、你还可以将程序打包分发,因为这些程序不需要被绑定到Django的安装环境中Edit thesettings.pyfile again, and change theINSTALLED_APPSsetting to include the stringpolls. So itll look like this:再次编辑settings.py文件,为INSTALLED_APPS加入“polls”。就像下面所显示的一样INSTALLED_APPS = ( django.contrib.auth, django.contrib.contenttypes, django.contrib.sessions

61、, 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,)Now Django knows to include thepollsapp. Lets run another co

62、mmand:现在Django就知道mysite项目中包含了polls程序了。现在我们执行另一条命令:python manage.py sql pollsYou should see something similar to the following (theCREATETABLESQL statements for the polls app):你应该能够看到类似于下面的输出(为polls程序的创建数据表的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;Note the following:请注意以下事项: The e

展开阅读全文
温馨提示:
1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
2: 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
3.本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
关于我们 - 网站声明 - 网站地图 - 资源地图 - 友情链接 - 网站客服 - 联系我们

copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!