Django官方教程(二)

来源:互联网 发布:ubuntu安装播放器 编辑:程序博客网 时间:2024/06/15 19:04

Writing your first Django app, part 2¶


编写你的第一个Django应用,第2部分

This tutorial begins where Tutorial 1 left off. We’ll setup the database, create your first model, and get a quick introduction to Django’s automatically-generated admin site.

本课程始于 Tutorial 1 结束。我们将要设置数据库,创建第一个模型,并且快速介绍Django自动创建的管理站点。

Database setup¶

数据库设置

Now, open up mysite/settings.py. It’s a normal Python module with module-level variables representing Django settings.

现在,打开mysite/settings.py。它是一个常规的Python模块,模块级变量代表Django的设置。

By default, the configuration uses SQLite. If you’re new to databases, or you’re just interested in trying Django, this is the easiest choice. SQLite is included in Python, so you won’t need to install anything else to support your database. When starting your first real project, however, you may want to use a more robust database like PostgreSQL, to avoid database-switching headaches down the road.

默认情况下,配置文件使用SQLite数据库。如果你刚接触数据库,或者你只对Django感兴趣,它是最省事儿的选择。因为SQLite已经包含在了Python中,所以你不用安装其他任何东西来提供数据库。然而,在开始第一个正式项目时,你可能想要使用更强大的数据库,像PostgreSQl数据库,来避免日后切换数据时头疼。

If you wish to use another database, install the appropriate database bindings and change the following keys in the DATABASES 'default' item to match your database connection settings:

如果你想要使用其他数据库,安装合适的 database bindings 并且更改DATABASES 'default' 下的键,来匹配你的数据库连接设置:

  • ENGINE – Either 'django.db.backends.sqlite3', 'django.db.backends.postgresql','django.db.backends.mysql', or 'django.db.backends.oracle'. Other backends are also available.
  • 引擎 ——可以用'django.db.backends.sqlite3', 'django.db.backends.postgresql','django.db.backends.mysql', 或'django.db.backends.oracle'.或者其他的后台也可以also available.。
  • NAME – The name of your database. If you’re using SQLite, the database will be a file on your computer; in that case,NAME should be the full absolute path, including filename, of that file. The default value, os.path.join(BASE_DIR,'db.sqlite3'), will store the file in your project directory.
  • 名称——你的数据库名字。如果你正在用SQLite,数据库将是你电脑上的一个文件,在这种情况下,NAME 应当是完整的绝对路径,包括文件名。默认值,os.path.join(BASE_DIR,'db.sqlite3'),将数据库存储在你的工程目录下。

If you are not using SQLite as your database, additional settings such as USER, PASSWORD, and HOST must be added. For more details, see the reference documentation for DATABASES.

如果你不是用SQLite作为你的数据库,其他额外的设置,像USERPASSWORD, 和 HOST必须添加上。更多细节,请查看相关的文档 DATABASES

For databases other than SQLite

如果数据库不是SQLite

If you’re using a database besides SQLite, make sure you’ve created a database by this point. Do that with “CREATE DATABASE database_name;” within your database’s interactive prompt.

如果你使用的数据库不是SQLite,请用这个方法确认你已经创建了一个数据库,在你的数据库交互提示中,输入“CREATE DATABASE database_name;”

Also make sure that the database user provided in mysite/settings.py has “create database” privileges. This allows automatic creation of a test database which will be needed in a later tutorial.

同时也要确保写在mysite/settings.py文件中的数据库用户有“创建数据库”的特权,这样是为了允许自动创建测试数据库test database,这将在后面的课程中用得到。

If you’re using SQLite, you don’t need to create anything beforehand - the database file will be created automatically when it is needed.

如果你正在用SQLite,你不需要实现创建任何东西-数据库文件在需要时将会自动创建。


While you’re editing mysite/settings.py, set TIME_ZONE to your time zone.

当你编辑mysite/setting.py时,设置时区TIME_ZONE 为你的时区。

Also, note the INSTALLED_APPS setting at the top 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.

同时,注意文件顶部已安装应用 INSTALLED_APPS 的设置。它包括了Django应用名称的集合,它们在这个Django实例中将被激活。应用可以被用在许多项目中,你也可以打包发布它们,让其他人在他们的项目中使用。

By default, INSTALLED_APPS contains the following apps, all of which come with Django:

默认情况下,INSTALLED_APPS 包含了如下应用,它们来自Django:

  • django.contrib.admin – The admin site. You’ll use it shortly.
  • django.contrib.admin – 管理员站点。很快,你将会很快用到它。
  • django.contrib.auth – An authentication system.
  • django.contrib.auth – 一个身份验证系统。
  • django.contrib.contenttypes – A framework for content types.
  • django.contrib.contenttypes – 一个内容类型框架。.
  • django.contrib.sessions – A session framework.
  • django.contrib.sessions – 一个session框架。
  • django.contrib.messages – A messaging framework.
  • django.contrib.messages – 一个消息框架。
  • django.contrib.staticfiles – A framework for managing static files.
  • django.contrib.staticfiles – 一个管理静态文件的框架。

These applications are included by default as a convenience for the common case.

默认情况下,这些应用被包括在内,为常见情况提供便利。

Some of these applications make 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:

这些应用中的个别应用至少在使用数据库中使用一张表,因此我们在使用它们之前前,需要在数据库中创建这些表。为此,运行下面的命令:

$ python manage.py migrate

The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file and the database migrations shipped with the app (we’ll cover those later). You’ll see a message for each migration it applies. If you’re interested, run the command-line client for your database and type \dt (PostgreSQL), SHOW TABLES; (MySQL), .schema (SQLite), or SELECT TABLE_NAME FROMUSER_TABLES; (Oracle) to display the tables Django created.

这个移植 migrate 命令查看已安装应用 INSTALLED_APPS 设置,然后根据你的mysite/settings.py 文件中的数据设置和应用附带的数据库迁移信息(我们将在后面覆盖它),创建必要的数据库表。你将会看到一个关于它所应用的每一个迁移信息的消息。如果你感兴趣,在你数据库的命令行客户端中输入 \dt (PostgreSQL), SHOW TABLES; (MySQL), .schema (SQLite), 或SELECT TABLE_NAME FROMUSER_TABLES; (Oracle)来显示Django创建的表。

For the minimalists

对极简主义者

Like we said above, the default applications are included for the common case, but not everybody needs them. If you don’t need any or all of them, feel free to comment-out or delete the appropriate line(s) fromINSTALLED_APPS before running migrate. The migrate command will only run migrations for apps inINSTALLED_APPS.

像我们上面所说的,通常情况下,默认应用是被包含在内的,但是并不是每个人都需要它。如果你不需要它们中的某些或是全部都不需要,可以在运行移植 migrate命令前从INSTALLED_APPS 中注释或删除掉合适的行。移植migrate 命令只运行已安装应用INSTALLED_APPS中的迁移信息。

Creating models¶

创建模型

Now we’ll define your models – essentially, your database layout, with additional metadata.

现在我们将要定义你的模型——本质上讲,就是展示你的数据库,包括附加的元数据

Philosophy

哲学

A model is the single, definitive source of truth about your data. It contains the essential fields and behaviors of the data you’re storing. Django follows the DRY Principle. The goal is to define your data model in one place and automatically derive things from it.

模型是关于数据真实性的唯一的,可靠的信息源。它包含了你存储的数据的必要字段和行为。Django遵从不要自我重复原则 DRY Principle。目的是在一个地方定义你的数据模型,然后自动从它派生出东西

This includes the migrations - unlike in Ruby On Rails, for example, migrations are entirely derived from your models file, and are essentially just a history that Django can roll through to update your database schema to match your current models.

这包含迁移信息——和Rails上的Ruby不同,例如,迁移信息是完全从你的模型文件中派生出来的,本质上讲就是一个历史文件——Django通过它更新你的数据库模式,达到匹配当前模型。

In our simple poll app, we’ll create two models: Question and Choice. A Question has a question and a publication date. A Choice has two fields: the text of the choice and a vote tally. Each Choice is associated with a Question.

在我们简单的投票应用中,我们将创建两个模型:问题模型和选项模型。一个问题模型有一个问题字段和创建日期字段。一个选项模型有两个字段:选项的文字和投票的票数。每一个选项模型关联一个问题模型。

These concepts are represented by simple Python classes. Edit the polls/models.py file so it looks like this:

这些概念被简单的Python类所代表。编辑polls/models.py文件,让它看起来像这样:

polls/models.py
from django.db import modelsclass Question(models.Model):    question_text = models.CharField(max_length=200)    pub_date = models.DateTimeField('date published')class Choice(models.Model):    question = models.ForeignKey(Question, on_delete=models.CASCADE)    choice_text = models.CharField(max_length=200)    votes = models.IntegerField(default=0)

The code is straightforward. Each model is represented by a class that subclasses django.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 a Field class – e.g., CharField for character fields and DateTimeField for datetimes. This tells Django what type of data each field holds.

每一个字段代表一个“ Field 类”的实例——例如, CharField 代表字符字段, DateTimeField 代表日期。这将告诉Django每一个字段是什么类型。

The name of each Field instance (e.g. question_text or pub_date) is the field’s name, in machine-friendly format. You’ll use this value in your Python code, and your database will use it as the column name.

在机器友好的格式化后,每一个 Field 类的实例名(例如,question_text或pub_date)代表一个字段名。你将会用到它的值,在Python代码中,而且你的数据库将用它作为列名。

You can use an optional first positional argument to a Field to designate a human-readable name. That’s used in a couple of introspective parts of Django, and it doubles as documentation. If this field isn’t provided, Django will use the machine-readable name. In this example, we’ve only defined a human-readable name for Question.pub_date. For all other fields in this model, the field’s machine-readable name will suffice as its human-readable name.

你可以对 Field 类用一个第一位置的可选参数,来表明一个人类可读的名字。它用在Django的一些内省部分,并且作为文档。如果这个字段没有提供,Django将用机器可读的名称。例如,我们只为问题模型的的pub_date字段定义了一个人们可读的名字。对于模型中其他的字段,字段的机器可读名足够作为它的人类可读名。

Some Field classes have required arguments. CharField, for example, requires that you give it a max_length. That’s used not only in the database schema, but in validation, as we’ll soon see.

一些 Field 类需要设置必要参数。例如,字符字段 CharField,需要你给它一个最大长度 max_length。 这不仅仅是用在数据库模式中,也用在校验中,马上我们就会看到。

A Field can also have various optional arguments; in this case, we’ve set the default value of votes to 0.

一个 Field 类可以有各种各样的可选参数;这种情况下,我们已经设置了票数的 default 值,为0。

Finally, note a relationship is defined, using ForeignKey. That tells Django each Choice is related to a single Question. Django supports all the common database relationships: many-to-one, many-to-many, and one-to-one.

最后,注意一个被定义的关系,使用外键 ForeignKey。它告诉Django每一个选项模型都关联唯一的一个问题模型。Django支持所有的常见数据库关系:多对一,多对多,和一对一。

Activating models¶

激活模型

That small bit of model code gives Django a lot of information. With it, Django is able to:

那些简短的代码给了Django大量的信息,用它,Django能够:

  • Create a database schema (CREATE TABLE statements) for this app.
  • 为这个应用创建数据库模式(创建表的语句)。
  • Create a Python database-access API for accessing Question and Choice objects.
  • 创建一个Python数据库访问的API用来访问问题和选项对象。

But first we need to tell our project that the polls app is installed.

但是首先我们需要告诉我们的项目polls应用已经安装了。

Philosophy

哲学

Django apps are “pluggable”: You can use an app in multiple projects, and you can distribute apps, because they don’t have to be tied to a given Django installation.

Django应用是“可插拔的”。你可以在许多项目中使用一个应用,并且你可以发布应用,因为它们没有被绑定到指定安装的Django中。

Edit the mysite/settings.py file again, and change the INSTALLED_APPS setting to include the string'polls.apps.PollsConfig'. It’ll look like this:

再次编辑mysite/settings.py文件,更改已安装应用 INSTALLED_APPS 设置,使它包含字符串'polls.apps.PollsConfig'.看起来像这样:

mysite/settings.py
INSTALLED_APPS = [    'polls.apps.PollsConfig',    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',]

Now Django knows to include the polls app. Let’s run another command:

现在Django知道包含了polls应用。让我运行另一个命令:

$ python manage.py makemigrations polls

You should see something similar to the following:

你将会看到如下内容:

Migrations for 'polls':  0001_initial.py:    - Create model Choice    - Create model Question    - Add field question to choice

By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.

通过运行迁移信息命令 makemigrations,你将告诉Django你对模型做出了一些更改(在这种情况下,你已经取得了一个新的)并且你想要将这些更改作为一个迁移信息存起来。

Migrations are how Django stores changes to your models (and thus your database schema) - they’re just files on disk. You can read the migration for your new model if you like; it’s the file polls/migrations/0001_initial.py. Don’t worry, you’re not expected to read them every time Django makes one, but they’re designed to be human-editable in case you want to manually tweak how Django changes things.

迁移信息Django存储了你的模型(也就是你数据库模式)做了怎样的更改,它们就是硬盘中的文件。如果你喜欢的话,可以阅读关于你的新模型的迁移信息;它是polls/migrations/0001_initial.py文件。别担心,你不会期望每次Django更改后就阅读它们,但它们被设计成可以人为编辑的,以防万一你想要手动调整Django更改的东西。

There’s a command that will run the migrations for you and manage your database schema automatically - that’s called migrate, and we’ll come to it in a moment - but first, let’s see what SQL that migration would run. The sqlmigratecommand takes migration names and returns their SQL:

有一个命令将会为你运行这些迁移信息并且自动管理你的数据库模式——它被称为移植命令 migrate,而且我们马上会介绍到它——但首先,让我们看看迁移将信息将要运行哪些SQL语句。 sqlmigrate命令后跟迁移信息名称会返回它们的SQL语句:

$ python manage.py sqlmigrate polls 0001

You should see something similar to the following (we’ve reformatted it for readability):

你会看到类似下面的内容(为了便于阅读我们已经将它排版优化):

BEGIN;---- Create model Choice--CREATE TABLE "polls_choice" (    "id" serial NOT NULL PRIMARY KEY,    "choice_text" varchar(200) NOT NULL,    "votes" integer NOT NULL);---- Create model Question--CREATE TABLE "polls_question" (    "id" serial NOT NULL PRIMARY KEY,    "question_text" varchar(200) NOT NULL,    "pub_date" timestamp with time zone NOT NULL);---- Add field question to choice--ALTER TABLE "polls_choice" ADD COLUMN "question_id" integer NOT NULL;ALTER TABLE "polls_choice" ALTER COLUMN "question_id" DROP DEFAULT;CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");ALTER TABLE "polls_choice"  ADD CONSTRAINT "polls_choice_question_id_246c99a640fbbd72_fk_polls_question_id"    FOREIGN KEY ("question_id")    REFERENCES "polls_question" ("id")    DEFERRABLE INITIALLY DEFERRED;COMMIT;

Note the following:

注意下面这些:

  • The exact output will vary depending on the database you are using. The example above is generated for PostgreSQL.
  • 准确的输出取决于你所用的数据库。上面的例子是由PostgreSQL产生的。
  • Table names are automatically generated by combining the name of the app (polls) and the lowercase name of the model – question and choice. (You can override this behavior.)
  • 表名是由app名字+小写的模型名——question和choice,自动命名的。(你可以覆盖这一行为。)
  • Primary keys (IDs) are added automatically. (You can override this, too.)
  • 主键(IDs)是自动添加的。(你也可以覆盖这个。)
  • By convention, Django appends "_id" to the foreign key field name. (Yes, you can override this, as well.)
  • 按照惯例,Django为外键列名添加“_id”。(是的,你也可以覆盖这个。)
  • The foreign key relationship is made explicit by a FOREIGN KEY constraint. Don’t worry about the DEFERRABLE parts; that’s just telling PostgreSQL to not enforce the foreign key until the end of the transaction.
  • 外键关系是由外键约束明确的。无需关注“DEFERRABLE”部分,它只是告诉PostgreSQL不要强制执行外键约束,直到事务结束。
  • It’s tailored to the database you’re using, so database-specific field types such as auto_increment (MySQL), serial(PostgreSQL), or integer primary key autoincrement (SQLite) are handled for you automatically. Same goes for the quoting of field names – e.g., using double quotes or single quotes.
  • 它针对你所使用的数据库,因此数据字的特殊字段,像 auto_increment (MySQL),, serial(PostgreSQL), 或者 integer primary key autoincrement (SQLite)能为你自动处理。同样也包括字段的引号——例如,使用双引号或单引号。
  • The sqlmigrate command doesn’t actually run the migration on your database - it just prints it to the screen so that you can see what SQL Django thinks is required. It’s useful for checking what Django is going to do or if you have database administrators who require SQL scripts for changes.
  •  sqlmigrate 并不是真的为你的数据库运行迁移——它仅仅是打印到屏幕上Django认为需要的SQL语句。

If you’re interested, you can also run python manage.py check; this checks for any problems in your project without making migrations or touching the database.

如果你感兴趣,你也可以运行 python manage.py check;用来检查你的项目问题,不需要运行迁移信息和接触数据库。

Now, run migrate again to create those model tables in your database:

现在,再次运行移植命令 migrate 来在你的数据库中创建这些模型表:

$ python manage.py migrateOperations to perform:  Apply all migrations: admin, contenttypes, polls, auth, sessionsRunning migrations:  Rendering model states... DONE  Applying polls.0001_initial... OK

The migrate command takes all the migrations that haven’t been applied (Django tracks which ones are applied using a special table in your database called django_migrations) and runs them against your database - essentially, synchronizing the changes you made to your models with the schema in the database.

移植 migrate 命令应用所有还没有被应用过的迁移信息(Django通过一个特殊的表,叫做django_migrations,来记录哪一个表被应用过)并且针对你的数据库运行它们——本质上讲,同步你的模型在数据库模式上的变化。

Migrations are very powerful and let you change your models over time, as you develop your project, without the need to delete your database or tables and make new ones - it specializes in upgrading your database live, without losing data. We’ll cover them in more depth in a later part of the tutorial, but for now, remember the three-step guide to making model changes:

迁移信息十分强大,可以让你一直更改你的模型,你只要开发你的项目,不需要删除数据库或者表然后新建一个——它专注于你数据库的实时升级,不丢失数据。我们在后面的课程将会深入介绍它,但是现在,记住改变模型的三个步骤:

  • Change your models (in models.py).
  • 更改你的模型(在models.py文件中)
  • Run python manage.py makemigrations to create migrations for those changes
  • 运行 python manage.py makemigrations 来为你的更改创建迁移
  • Run python manage.py migrate to apply those changes to the database.
  • 运行 python manage.py migrate  对数据库应用那些修改

The reason that there are separate commands to make and apply migrations is because you’ll commit migrations to your version control system and ship them with your app; they not only make your development easier, they’re also useable by other developers and in production.

用分开的命令创建和应用迁移信息是因为你将提交迁移信息到你的版本控制器中并且使它们能跟随你的应用;这不仅使你开发更容易,也可以方便这个产品中的其他开发者。

Read the django-admin documentation for full information on what the manage.py utility can do.

阅读 django-admin documentation 了解manage.py能做的所有信息

Playing with the API¶

调用API

Now, let’s hop into the interactive Python shell and play around with the free API Django gives you. To invoke the Python shell, use this command:

现在,让我们跳入Python的交互shell然后调用免费的API Django的给你。要调用Python的外壳,使用这个命令:

$ python manage.py shell

We’re using this instead of simply typing “python”, because manage.py sets the DJANGO_SETTINGS_MODULE environment variable, which gives Django the Python import path to your mysite/settings.py file.

我用使用这个来代替输入“python”,因为manage.py设置了 DJANGO_SETTINGS_MODULE 的环境变量,它为Django提供了Python到你mysite/settings.py  文件的导入路径。

Bypassing manage.py

绕过manage.py

If you’d rather not use manage.py, no problem. Just set the DJANGO_SETTINGS_MODULE environment variable to mysite.settings, start a plain Python shell, and set up Django:

如果你不想用manage.py,没问题。只需要为mysite.settings设置 DJANGO_SETTINGS_MODULE 环境变量,打开一个新的Python shell,然后设置Django

>>> import django>>> django.setup()

If this raises an AttributeError, you’re probably using a version of Django that doesn’t match this tutorial version. You’ll want to either switch to the older tutorial or the newer Django version.

如果这样做引起一个属性异常 AttributeError,你可能使用的Django版本和本课程版本不匹配。你可以转换到旧版本课程或者更新Django版本。

You must run python from the same directory manage.py is in, or ensure that directory is on the Python path, so that import mysite works.

你必须从manage.py文件项相同的目录下运行python,或者确认目录在Python路径下,只有这样import mysite才能生效。

For more information on all of this, see the django-admin documentation.

获得更多信息,请看 django-admin documentation

Once you’re in the shell, explore the database API:

一旦你正在运行shell,查看 database API

>>> from polls.models import Question, Choice   # Import the model classes we just wrote.# No questions are in the system yet.>>> Question.objects.all()[]# Create a new Question.# Support for time zones is enabled in the default settings file, so# Django expects a datetime with tzinfo for pub_date. Use timezone.now()# instead of datetime.datetime.now() and it will do the right thing.>>> from django.utils import timezone>>> q = Question(question_text="What's new?", pub_date=timezone.now())# Save the object into the database. You have to call save() explicitly.>>> q.save()# Now it has an ID. Note that this might say "1L" instead of "1", depending# on which database you're using. That's no biggie; it just means your# database backend prefers to return integers as Python long integer# objects.>>> q.id1# Access model field values via Python attributes.>>> q.question_text"What's new?">>> q.pub_datedatetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)# Change values by changing the attributes, then calling save().>>> q.question_text = "What's up?">>> q.save()# objects.all() displays all the questions in the database.>>> Question.objects.all()[<Question: Question object>]

Wait a minute. <Question: Question object> is, utterly, an unhelpful representation of this object. Let’s fix that by editing the Question model (in the polls/models.py file) and adding a __str__() method to both Question and Choice:

等下。 对这个对象来说,<Question: Question object> 是一个完全没有用的提示。让我们通过修改Question模型(在polls/models.py文件)然后为Question和Choice添加一个 __str__() 方法来修正它:

polls/models.py
from django.db import modelsfrom django.utils.encoding import python_2_unicode_compatible@python_2_unicode_compatible  # only if you need to support Python 2class Question(models.Model):    # ...    def __str__(self):        return self.question_text@python_2_unicode_compatible  # only if you need to support Python 2class Choice(models.Model):    # ...    def __str__(self):        return self.choice_text

It’s important to add __str__() methods to your models, not only for your own convenience when dealing with the interactive prompt, but also because objects’ representations are used throughout Django’s automatically-generated admin.

为你的模型添加 __str__() 很重要,不仅是为了你交互时的便利,也因为对象的表示始终被Django的自动生成的管理员使用。

Note these are normal Python methods. Let’s add a custom method, just for demonstration:

注意这些是Python的正常方法。让我们添加一个习惯方法,仅做示范:

polls/models.py
import datetimefrom django.db import modelsfrom django.utils import timezoneclass Question(models.Model):    # ...    def was_published_recently(self):        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

Note the addition of import datetime and from django.utils import timezone, to reference Python’s standard datetime module and Django’s time-zone-related utilities in django.utils.timezone, respectively. If you aren’t familiar with time zone handling in Python, you can learn more in the time zone support docs.

注意增加的 import datetime 和 from django.utils import timezone, 分别涉及到Python的标准 datetime 模块和Django的相关时区公共设置在 django.utils.timezone,。如果你不熟悉Python的时区处理,你可以到 time zone support docs了解更多。

Save these changes and start a new Python interactive shell by running python manage.py shell again:

保存这些更改然后通过再次运行python manage.py shell新开一个Python交互shell,:

>>> from polls.models import Question, Choice# Make sure our __str__() addition worked.>>> Question.objects.all()[<Question: What's up?>]# Django provides a rich database lookup API that's entirely driven by# keyword arguments.>>> Question.objects.filter(id=1)[<Question: What's up?>]>>> Question.objects.filter(question_text__startswith='What')[<Question: What's up?>]# Get the question that was published this year.>>> from django.utils import timezone>>> current_year = timezone.now().year>>> Question.objects.get(pub_date__year=current_year)<Question: What's up?># Request an ID that doesn't exist, this will raise an exception.>>> Question.objects.get(id=2)Traceback (most recent call last):    ...DoesNotExist: Question matching query does not exist.# Lookup by a primary key is the most common case, so Django provides a# shortcut for primary-key exact lookups.# The following is identical to Question.objects.get(id=1).>>> Question.objects.get(pk=1)<Question: What's up?># Make sure our custom method worked.>>> q = Question.objects.get(pk=1)>>> q.was_published_recently()True# Give the Question a couple of Choices. The create call constructs a new# Choice object, does the INSERT statement, adds the choice to the set# of available choices and returns the new Choice object. Django creates# a set to hold the "other side" of a ForeignKey relation# (e.g. a question's choice) which can be accessed via the API.>>> q = Question.objects.get(pk=1)# Display any choices from the related object set -- none so far.>>> q.choice_set.all()[]# Create three choices.>>> q.choice_set.create(choice_text='Not much', votes=0)<Choice: Not much>>>> q.choice_set.create(choice_text='The sky', votes=0)<Choice: The sky>>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)# Choice objects have API access to their related Question objects.>>> c.question<Question: What's up?># And vice versa: Question objects get access to Choice objects.>>> q.choice_set.all()[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>>> q.choice_set.count()3# The API automatically follows relationships as far as you need.# Use double underscores to separate relationships.# This works as many levels deep as you want; there's no limit.# Find all Choices for any question whose pub_date is in this year# (reusing the 'current_year' variable we created above).>>> Choice.objects.filter(question__pub_date__year=current_year)[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]# Let's delete one of the choices. Use delete() for that.>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')>>> c.delete()

For more information on model relations, see Accessing related objects. For more on how to use double underscores to perform field lookups via the API, see Field lookups. For full details on the database API, see our Database API reference.

想要连接更多有关关系型数据库,请看Accessing related objects.。想要知道更多关于如何使用双下划线来进行API现场查询,请看 Field lookups。想要了解更多数据库API,请看我们的Database API reference。

Introducing the Django Admin¶

介绍Django管理站点

Philosophy

哲学

Generating admin sites for your staff or clients to add, change, and delete content is tedious work that doesn’t require much creativity. For that reason, Django entirely automates creation of admin interfaces for models.

为你的员工或者客户创建管理站点来进行添加,修改和删除是无聊的工作,它不会获得创造力。因此,Django为模型自动创建完整的管理接口。

Django was written in a newsroom environment, with a very clear separation between “content publishers” and the “public” site. Site managers use the system to add news stories, events, sports scores, etc., and that content is displayed on the public site. Django solves the problem of creating a unified interface for site administrators to edit content.

Django是写在编辑部环境下,和“内容出版”与“公共”网站之间有明显区分。站点管理员用这个系统来添加新闻故事,事件,体育分数等,并且这些内容是显示在公共站点。Django解决了为管理员创建一个统一编辑内容接口的问题。

The admin isn’t intended to be used by site visitors. It’s for site managers.

管理站点不是让访客来使用的。是为站点管理员的。

Creating an admin user¶

创建一个管理员

First we’ll need to create a user who can login to the admin site. Run the following command:

首先我们要创建一个能登录管理员站点的用户。运行如下命令:

$ python manage.py createsuperuser

Enter your desired username and press enter.

输入你想要的用户名并按回车:

Username: admin

You will then be prompted for your desired email address:

接下来你将看到输入邮箱的提示:

Email address: admin@example.com

The final step is to enter your password. You will be asked to enter your password twice, the second time as a confirmation of the first.

最后一个是输入你的密码。你将被要求输入密码两次,第二次是为了确认密码。

Password: **********Password (again): *********Superuser created successfully.

Start the development server¶

启动开发版服务

The Django admin site is activated by default. Let’s start the development server and explore it.

Django管理员站点默认被激活。让我们开启开发调试服务器来查看它。

If the server is not running start it like so:

如果服务没有运行,像这样启动它:

$ python manage.py runserver

Now, open a Web browser and go to “/admin/” on your local domain – e.g., http://127.0.0.1:8000/admin/. You should see the admin’s login screen:

现在,打开一个浏览器在你本地域名下输入“/admin/”——例如, http://127.0.0.1:8000/admin/. 你将会看到管理员登录页:

Django admin login screen

Since translation is turned on by default, the login screen may be displayed in your own language, depending on your browser’s settings and if Django has a translation for this language.

因为 translation 是被默认开启的,登录界面可能显示的是你的语言,取决于你的浏览器设置并且如果Django已经为这个语言翻译过。

Enter the admin site¶

进入管理员站点

Now, try logging in with the superuser account you created in the previous step. You should see the Django admin index page:

现在,试着登录你之前创建的管理员账户。你会看到Django管理员主页:

Django admin index page

You should see a few types of editable content: groups and users. They are provided by django.contrib.auth, the authentication framework shipped by Django.

你会看见一些可编辑的内容:组和用户。它由 django.contrib.auth提供,Django附带的认证框架。

Make the poll app modifiable in the admin¶

让投票应用在管理后台中可修改

But where’s our poll app? It’s not displayed on the admin index page.

但是我们的投票应用在哪里?它并没有显示在管理后台的主页

Just one thing to do: we need to tell the admin that Question objects have an admin interface. To do this, open the polls/admin.py file, and edit it to look like this:

只需要做一件事:我们需要告诉管理后台Question对象有一个管理接口。为了做到这,打开polls/admin.py文件,并且编辑它,使它看起来像这样:

polls/admin.py
from django.contrib import adminfrom .models import Questionadmin.site.register(Question)

Explore the free admin functionality¶

查看自由风格的管理功能

Now that we’ve registered Question, Django knows that it should be displayed on the admin index page:

现在我们已经注册了Question,Django知道它应该显示在admin主页:

Django admin index page, now with polls displayed

Click “Questions”. Now you’re at the “change list” page for questions. This page displays all the questions in the database and lets you choose one to change it. There’s the “What’s up?” question we created earlier:

点击“Question”。现在你在Question的“待更改列表”页。该页显示数据库中所有的问题并且让你选择一个来更改。有“What's up?”我们早期创建的一个问题。

Polls change list page

Click the “What’s up?” question to edit it:

点击问题“What's up?”来编辑它:

Editing form for question object

Things to note here:

这里需要注意的事:

  • The form is automatically generated from the Question model.
  • 这些表单是根据问题模型自动生成的。
  • The different model field types (DateTimeField, CharField) correspond to the appropriate HTML input widget. Each type of field knows how to display itself in the Django admin.
  • 不同的模型字段类型(DateTimeFieldCharField)对应恰当的HTML输入部件。在Django管理站点中每一种字段类型知道如何显示它自身。
  • Each DateTimeField gets free JavaScript shortcuts. Dates get a “Today” shortcut and calendar popup, and times get a “Now” shortcut and a convenient popup that lists commonly entered times.
  • 每一个日期时间字段 DateTimeField 都有免费的JavaScripts快捷方式。日期有一个“Today”快捷键并且弹出日历,时间有“Now”快捷键并且一进入时间就便捷的弹出列表。

The bottom part of the page gives you a couple of options:

页面的底部给你了一些选项:

  • Save – Saves changes and returns to the change-list page for this type of object.
  • 保存——保存更改并且返回到这类对象的列表页。
  • Save and continue editing – Saves changes and reloads the admin page for this object.
  • 保存并继续更改——保存更改并且重新加载该对象的管理页。
  • Save and add another – Saves changes and loads a new, blank form for this type of object.
  • 保存并添加下一个——保存更改并且加载一个新的,该类型对象的空白表单。
  • Delete – Displays a delete confirmation page.
  • 删除——显示一个删除确认页。

If the value of “Date published” doesn’t match the time when you created the question in Tutorial 1, it probably means you forgot to set the correct value for the TIME_ZONE setting. Change it, reload the page and check that the correct value appears.

如果“Date published”的值和你在第一课创建问题时不匹配,这可能意味着你忘记设置正确的 TIME_ZONE 设置。更改它,重新加载本页并检查,正确的值将显示。

Change the “Date published” by clicking the “Today” and “Now” shortcuts. Then click “Save and continue editing.” Then click “History” in the upper right. You’ll see a page listing all changes made to this object via the Django admin, with the timestamp and username of the person who made the change:

通过点击“Today”和“Now”快捷方式来更改“Date published”。然后点击“Save and continue editing.”然后点击右上方的“History”。你将会看到一个页面展示着该对象的所有更改记录,并且有时间戳和进行操作更改的用户名。

History page for question object

When you’re comfortable with the models API and have familiarized yourself with the admin site, read part 3 of this tutorial to learn about how to add more views to our polls app.

当你适应了模型API和数据了管理员站点后,阅读part 3 of this tutorial来学习如何添加更多的视图到你的app中。

0 0
原创粉丝点击