Django文档阅读-Day2

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Django文档阅读-Day2

coderchen01   2020-04-24 我要评论

Django文档阅读 - Day2

Writing your first Django app, part 1

You can tell Django is installed and which version by running the following command in a shell prompt.

$ python -m django --version

Creating a project

If this is your first time using Django, you’ll have to take care of some initial setup. Namely, you’ll need to auto-generate some code that establishes a Django project – a collection of settings for an instance of Django, including database configuration, Django-specific options and application-specific settings.

From the command line, cd into a directory where you’d like to store your code, then run the following command:

$ django-admin startproject [name]

通过自动生成代码建立一个Django Project。

This will create a mysite directory in your current directory. If it didn’t work, see Problems running django-admin.

Let’s look at what startproject created:

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

These files are:

  • The outer mysite/ root directory is a container for your project. Its name doesn’t matter to Django; you can rename it to anything you like.

  • 最外层的mysite文件名不会影响Django工作

  • manage.py: A command-line utility that lets you interact with this Django project in various ways. You can read all the details about manage.py in django-admin and manage.py.

  • The inner mysite/ directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it (e.g. mysite.urls).

  • 内层的mysite文件夹是一个Python包。

  • mysite/__init__.py: An empty file that tells Python that this directory should be considered a Python package. If you’re a Python beginner, read more about packages in the official Python docs.

  • 告诉Python这个文件夹是一个包。

  • mysite/settings.py: Settings/configuration for this Django project. Django settings will tell you all about how settings work.

  • mysite/urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site. You can read more about URLs in URL dispatcher.

  • mysite/asgi.py: An entry-point for ASGI-compatible web servers to serve your project. See How to deploy with ASGI for more details.

  • mysite/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project. See How to deploy with WSGI for more details.

The development server

Let’s verify your Django project works. Change into the outer mysite directory, if you haven’t already, and run the following commands:

$ python manage.py runserver

You’ve started the Django development server, a lightweight Web server written purely in Python. We’ve included this with Django so you can develop things rapidly, without having to deal with configuring a production server – such as Apache – until you’re ready for production.

你已经启动了Django开发服务器,一个纯粹使用Python开发的轻量级Web服务器。我们在Django中内置了这个服务器,这样你就可以迅速开发了,在产品投入使用之前不必去配置一台生产环境下的服务器---例如Apache.

Now’s a good time to note: don’t use this server in anything resembling a production environment. It’s intended only for use while developing. (We’re in the business of making Web frameworks, not Web servers.

现在最佳提示时间,千万不要在任何类似于生产环境下使用开发服务器。

Now that the server’s running, visit http://127.0.0.1:8000/ with your Web browser. You’ll see a “Congratulations!” page, with a rocket taking off. It worked!

可通过一下方式改变端口

$ python manage.py runserver [port]

If you want to change the server’s IP, pass it along with the port. For example, to listen on all available public IPs (which is useful if you are running Vagrant or want to show off your work on other computers on the network), use:

$ python manage.py runserver [ip:port]
$ python manage.py runserver 0:8080

Automatic reloading of runserver

The development server automatically reloads Python code for each request as needed. You don’t need to restart the server for code changes to take effect. However, some actions like adding files don’t trigger a restart, so you’ll have to restart the server in these cases.

通常runserver之后会自动加载修改后的代码,但是呢,如果是添加了某个文件,就需要重启服务了。修改代码不必重启服务,会触发Django自动重加载。

Creating the Polls app

Now that your environment – a “project” – is set up, you’re set to start doing work.

既然环境配置好了,你就准备开始吧。

Each application you write in Django consists of a Python package that follows a certain convention. Django comes with a utility that automatically generates the basic directory structure of an app, so you can focus on writing code rather than creating directories.

Django的每一个app都会包含一个遵循某些约定的Python包。Django有一个自动生成app目录结构的工具,所以你可以集中于编写目录,而不是创建目录。

Projects vs. apps

What’s the difference between a project and an app? An app is a Web application that does something – e.g., a Weblog system, a database of public records or a small poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.

项目与应用的不同之处?应用是一个Web应用,它可以做很多事,比如一个日志系统,一个公有数据库,或者一个投票app。一个项目是配置和应用的集合。一个项目可以包含多个应用,同时一个应用可以用于多个项目。(哇,高度解耦)

Your apps can live anywhere on your Python path. In this tutorial, we’ll create our poll app in the same directory as your manage.py file so that it can be imported as its own top-level module, rather than a submodule of mysite.

**你的app可以创建在任意一个Python可以找到的位置(sys.path),不一定非要创建在当前目录哦(不要思维定式了,我们将创建我们的投票app在manage.py文件所在位置。这样我们app可以被作为顶级模块导入,而不是mysite的一个子模块。

To create your app, make sure you’re in the same directory as manage.py and type this command:

$ python manage.py startapp polls

That'll create a directory polls, which is laid out like this:

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

Write your first view

Let’s write the first view. Open the file polls/views.py and put the following Python code in it:

from django.http import HttpResponse #HttpResponse 在http中哦,记住位置啦


def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

This is the simplest view possible in Django. To call the view, we need to map it to a URL - and for this we need a URLconf.

To create a URLconf in the polls directory, create a file called urls.py. Your app directory should now look like:

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    urls.py
    views.py

In the polls/urls.py file include the following code:

from django.urls import path #记住啦,path在urls中。

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

The next step is to point the root URLconf at the polls.urls module. In mysite/urls.py, add an import for django.urls.include and insert an include() in the urlpatterns list, so you have:

在项目URL配置中建立映射关系:

from django.contrib import admin
from django.urls import include, path #include也在urls里面哦,路径相关的都封装在了urls

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

The include() function allows referencing other URLconfs. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.

The idea behind include() is to make it easy to plug-and-play URLs. Since polls are in their own URLconf (polls/urls.py), they can be placed under “/polls/”, or under “/fun_polls/”, or under “/content/polls/”, or any other path root, and the app will still work.

include() 函数允许引用其他URLconfs. 每当Django遇到include()时,它会截断与该点匹配的URL的任何部分,并将剩余的字符串发送到包含的URLconf以供进一步处理。

使用include()的目的是为了让URL更易进行热插拔(plug-and-play)。 由于polls是在他自己的URLconfpolls/urls.py),他们可以被放置在“/ polls /”,或“/ fun_polls /”下,或“/ content / polls /” ,或任何其他路径的根,应用程序将仍然工作。

You have now wired an index view into the URLconf. Verify it’s working with the following command:

$ python manage.py runserver

The path() function is passed four arguments, two required: route and view, and two optional: kwargs, and name. At this point, it’s worth reviewing what these arguments are for.

path()参数:route 
route是一个包含URL模式的字符串。 在处理请求时,Django从urlpatterns中的第一个正则开始并在列表中向下匹配,将所请求的URL与每个正则进行匹配,直到找到匹配的正则。

正则表达式不搜索GET和POST参数或域名。 例如,在https://www.example.com/myapp/的请求中,URLconf将查找myapp /。 在https://www.example.com/myapp/?page=3的请求中,URLconf也会查找myapp/。

path()参数:view 
当Django找到匹配的正则时,它会以HttpRequest对象作为第一个参数和route中的任何“捕获”值作为关键字参数来调用指定的视图函数。 我们将稍微举一个例子。

path()参数:kwargs 
任意关键字参数可以在字典中传递给目标视图。 我们不打算在教程中使用Django的这个特性。

path()参数:name 
命名您的URL可以让您从Django其他地方明确地引用它,特别是在模板中。 这个强大的功能允许您在只操作单个文件的情况下对项目的URL正则进行全局更改。

当您熟悉基本的请求和响应流程时,请阅读本教程的第2部分以开始使用数据库。

Writing your first Django app, part 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.

Database setup

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

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 scalable database like PostgreSQL, to avoid database-switching headaches down the road.

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:

  • ENGINE – Either 'django.db.backends.sqlite3', 'django.db.backends.postgresql', 'django.db.backends.mysql', or 'django.db.backends.oracle'. Other backends are 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.

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.

For databases other than 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.

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.

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

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

在编辑mysite/settings.py时,一定要先设置自己的时区哦。

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.contrib.admin – The admin site. You’ll use it shortly. 管理站点
  • django.contrib.auth – An authentication system. 认证授权系统
  • django.contrib.contenttypes – A framework for content types. 内容类型框架
  • django.contrib.sessions – A session framework. 会话框架
  • django.contrib.messages – A messaging framework. 消息框架
  • django.contrib.staticfiles – A framework for managing static files. 管理静态文件的框架。这些应用被默认启用,为了给项目提供方便。

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).

这句话告诉我们在创建app是一定要在INSTALLED_APPS中注册,否则无法创建数据库的表哦

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; (MariaDB, MySQL), .schema (SQLite), or SELECT TABLE_NAME FROM USER_TABLES; (Oracle) to display the tables Django created.

migrate命令查看INSTALLED_APPS设置,并根据mysite/settings.py文件中的数据库设置创建所有必要的数据库表,迁移命令将只对Insted_app中的应用程序运行迁移。 You’ll see a message for each migration it applies. 如果你感兴趣的话, 运行你的数据库命令行客户端并且输入命令\dt (PostgreSQL), SHOW TABLES; (MySQL), .schema (SQLite), 或者 SELECT TABLE_NAME FROM USER_TABLES; (Oracle) 来显示Django创建的表

就像我们上面所说的那样,默认应用程序包含在常见的情况下,但不是每个人都需要它们。 如果您不需要其中任何一个或全部,请在运行migrate之前自由注释或删除INSTALLED_APPS中的相应行。 migrate命令将只对INSTALLED_APPS中的应用程序进行迁移。

Creating models

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

模型也就是数据库设计和附加的其他元数据。

设计哲学
模型是关于您的数据的单一,明确的真相来源。 它包含您正在存储的数据的重要字段和行为。 Django 遵循 DRY 原理. 目标是在一个地方定义你的数据模型,并从中自动派生东西。

这包括迁移 - 与Ruby On Rails不同,例如,迁移完全从您的模型文件派生而来,本质上只是Django可以滚动更新数据库模式以符合当前模型的历史记录。

In our 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 Python classes. Edit the polls/models.py file so it looks like this:

from django.db import models


class 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)

Here, 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表示——例如,用于字符字段的CharFieldDateTimeField。 这告诉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_textpub_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.

您可以使用可选的第一个位置参数指向一个字段来指定一个人类可读的名称。 这在Django的一些内省部分中使用,并且它作为文档加倍。 如果未提供此字段,则Django将使用机器可读名称。 在这个例子中,我们只为Question.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也可以有各种可选的参数;在这种情况下,我们已将votesdefault值设置为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每个Choice都与单个Question有关(多对一)。 Django支持所有常见的数据库关系:多对一,多对多和一对一。

Activating models

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

  • Create a database schema (CREATE TABLE statements) for this app.
  • Create a Python database-access API for accessing Question and Choice objects.

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

设计哲学
Django应用程序是“可插入的”:您可以在多个项目中使用应用程序,并且可以分发应用程序,因为它们不必绑定到当前安装的Django上。

To include the app in our project, we need to add a reference to its configuration class in the INSTALLED_APPS setting. The PollsConfig class is in the polls/apps.py file, so its dotted path is 'polls.apps.PollsConfig'. Edit the mysite/settings.py file and add that dotted path to the INSTALLED_APPS setting. It’ll look like this:

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:

$ python manage.py makemigrations polls

You should see something similar to the following:

Migrations for 'polls':
  polls/migrations/0001_initial.py
    - Create model Question
    - Create model 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你已经对你的models做出了改变,并且你想要储存为数据库迁移文件。

Migrations are how Django stores changes to your models (and thus your database schema) - they’re 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里。别担心,你不需要每次阅读它们,但是它们被设计成人类可读形式,这是为了便于你手动修改它们。

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 sqlmigrate command takes migration names and returns their SQL:

$ python manage.py sqlmigrate polls 001

Django有一个自动执行数据库迁移并同步管理你的数据结构的命令这个命令就是migrate,我们马上就会接触他,但是首先,让我们看看迁移命令会执行那些SQL语句。sqlmigrate命令接收一个迁移的名称,然后返回对应的SQL

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

BEGIN;
--
-- 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
);
--
-- Create model Choice
--
CREATE TABLE "polls_choice" (
    "id" serial NOT NULL PRIMARY KEY,
    "choice_text" varchar(200) NOT NULL,
    "votes" integer NOT NULL,
    "question_id" integer NOT NULL
);
ALTER TABLE "polls_choice"
  ADD CONSTRAINT "polls_choice_question_id_c5b4b260_fk_polls_question_id"
    FOREIGN KEY ("question_id")
    REFERENCES "polls_question" ("id")
    DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");

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.)

表名是通过将应用程序的名称(polls)和模型的小写名称questionchoice组合自动生成的。 (您可以覆盖此行为。)

  • Primary keys (IDs) are added automatically. (You can override this, too.)

主键(ID)会自动添加。 (你也可以覆盖它。)

  • 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; it’s telling PostgreSQL to not enforce the foreign key until the end of the transaction.

外键关系通过FOREIGN KEY约束来显式化。 不要担心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 - instead, it 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命令实际上并不在数据库上运行迁移 - 它只是将它打印到屏幕上,以便您可以看到SQL Django认为需要什么。 这对于检查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;这可以检查项目中的任何问题,且不会对数据库进行操作。

现在,再次运行migrate以在您的数据库中创建这些模型表:

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

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running 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).
  • Run python manage.py makemigrations to create migrations for those changes
  • Run python manage.py migrate to apply those changes to the database.

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 usable by other developers and in production.

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

在Day1中我猜测,数据迁移命令由一步变两步的原因有误,这里Django官方给出了答案:数据库迁移被分解成生成和应用两个命令是为了让开发者能够在代码控制系统中提交迁移数据并使其能够在多个应用中使用;这不仅会使的开发更加简单,也给别的开发者和生产环境中的使用带来了方便。

Playing with the 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 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.

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

>>> from polls.models import Choice, Question  # Import the model classes we just wrote.

# No questions are in the system yet.
>>> Question.objects.all()
<QuerySet []>

# 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 #划重点,Django中使用时间,现在设置中设置自己的时区,之后使用python提供的时间工具。在utils中,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.
>>> q.id
1

# Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.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()
<QuerySet [<Question: Question object (1)>]>

Wait a minute. <Question: Question object (1)> isn’t a helpful 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:

from django.db import models

class Question(models.Model):
    # ...
    def __str__(self):
        return self.question_text #打印对象是有人性化的提示

class 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__()不仅为了自己调试方便,admin还对其有所依赖。

Let’s also add a custom method to this model:

import datetime

from django.db import models
from django.utils import timezone


class 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.

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

>>> from polls.models import Choice, Question

# Make sure our __str__() addition worked.
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>

# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')
<QuerySet [<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()
<QuerySet []>

# 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()
<QuerySet [<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)
<QuerySet [<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.

Introducing the Django Admin

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 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.

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.

If the server is not running start it like so:

$ python manage.py runserver

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

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提供的,这是Python开发的认证框架。

Make the poll app modifiable in the admin

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

Only one more 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文件,把它编辑成下面这样:

from django.contrib import admin

from .models import Question

admin.site.register(Question)

Explore the free admin functionality

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.
  • 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.

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.

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

今日收获单词

throughout 遍及,贯穿
walk 引导
poll 投票
vote 投票,选举
assume 假设,设想
compatible 兼容的,能共处的
namely 也就是,换句话说
take care of 注意
conflict 冲突
risk 冒...风险
utility  /juːˈtɪləti/  实用,实用程序
interact 相互作用,互相影响,交互
dispatcher 调度员,调度程序
identify iden tify 确认,认出,鉴定,找到,发现
unapplied 未被应用
resemble re sem ble 看起来像(not used in the progressive tenses)
internal 内部的
show off 炫耀
be set to 准备
certain 某些,确实,确定,无疑
convention 习惯,习俗,约定
come with 与...一起,伴随着
house v.覆盖,把...储藏在房内
be laid out 展开
encounter 遭遇,邂逅,遇到
counter n.柜台,计数器 v.反击,还击,反驳
chop off 砍掉
arbitrary 任意的,专制的,武断的
leave off 中断,停止
head over 前往,驶往
hold 拥有,包含
make use of 利用,使用
essential 本质上,必要的;本质,要素,要点
derive 源于,得自,获得
definitive 明确的,最佳的
machine 机器机械
machine-friendly 机器友好的
introspective 内省的,反省的
tweak 扭,轻微调整
by convention 按照惯例
tailored 定制的,裁缝做的
transaction 事务,交易
deferrabel 可延期的,可退吃的
over time 随着时间的过去
specialize  专门从事;详细说明;特化
invoke 调用
interactive 交互式的
hop into 跳进,进入
hop 单足跳行
respectively 分别地,各自地,独自地
exact 准确的,精密的,要求,强求
lookup 查询
identical 完全相同的,同一的
construct 概念,设计,构图
tedious 沉闷的,冗长乏味的
automate 使自动化,自动化
unified 统一的,一致标准的
unify 统一,使一致
explore 探索
modifiable 可修改的

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们