快速入门Django(官网流程)2

快速入门Django(官网流程)2

本文是入门级操作,可以看作是官网的翻译版本,可直接照我的流程操作,
附上官网:
https://www.djangoproject.com/start/

OK,我们完成了第一步以后,接下来setup database,create your first model,
还有个quick introduction to Django’s automatically-generated admin site.

Database setup

打开 mysite/settings.py. It’s a normal Python module with module-level variables representing Django settings.
默认情况下,配置使用SQLite。

如果要使用其他数据库,请安装相应的数据库绑定并更改项中的以下键 以匹配数据库连接设置:DATABASES ‘default’
这里设置:
ENGINE- ‘django.db.backends.sqlite3’,其他后端也可以用
NAME - 数据库的名称,及文件路径。

在mysite/settings.py,设置TIME_ZONE为您的时区。

默认情况下,INSTALLED_APPS包含以下应用程序,所有这些应用程序都随Django一起提供:

django.contrib.admin - 管理站点。你很快就会用到它。
django.contrib.auth - 认证系统。
django.contrib.contenttypes - 内容类型的框架。
django.contrib.sessions - 会话框架。
django.contrib.messages - 消息传递框架。
django.contrib.staticfiles - 用于管理静态文件的框架。
默认情况下包含这些应用程序,以方便常见情况。

但,这些应用程序至少使用了一个数据库表
在数据库中创建表,运行以下命令:

python manage.py migrate

     
     
  • 1

显示

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK

     
     
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

OK

migrate命令查看INSTALLED_APPS设置并根据mysite/settings.py文件中的数据库设置和应用程序附带的数据库迁移创建任何必要的数据库表(稍后我们将介绍这些表)。

创建模型Creating models

现在将使用其他元数据定义模型 - 本质上是数据库布局。

模型是关于数据的单一,明确的真实来源。它包含您要存储的数据的基本字段和行为。
Django遵循DRY原则-Don’t repeat yourself (DRY)。目标是在一个地方定义您的数据模型,并自动从中获取数据。

在我们的简单民意调查应用程序中,我们将创建两个模型:Question和Choice。
A Question有问题和出版日期。A Choice有两个字段:选择的文本和投票记录。每个Choice都与a相关联Question。
编辑 polls/models.py文件

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)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

每个模型由一个子类表示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.

The name of each Field instance (e.g. question_text or pub_date) is the field’s name

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.

激活模型Activating models

这一小部分模型代码为Django提供了大量信息。有了它,Django能够:

  1. 为此应用程序创建数据库模式(语句)。CREATE TABLE
  2. 创建用于访问Question和Choice对象的Python数据库访问API 。
    但首先,需要告诉我们的项目polls应用程序已安装。

要在我们的项目中包含应用程序,我们需要在设置中添加对其配置类的引用INSTALLED_APPS。
该 PollsConfig class 是在polls/apps.py文件中,所以它的虚线路径’polls.apps.PollsConfig’。
编辑mysite/settings.py文件并将该虚线路径添加到INSTALLED_APPS设置中。

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’,
]

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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

$ python manage.py makemigrations polls

 
 
  • 1

You should see something similar to the following:

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

 
 
  • 1
  • 2
  • 3
  • 4
  • 5

通过运行makemigrations,迁移模型,告诉Django您已对模型进行了一些更改(但是需已经创建了新模型)
You can read the migration for your new model if you like; it’s the file polls/migrations/0001_initial.py.

they’re designed to be human-editable in case you want to manually tweak how Django changes things.
migrate语句,可以运行迁移并自动管理您的数据库模式

The sqlmigrate command takes migration names and returns their SQL:

python manage.py sqlmigrate polls 0001

 
 
  • 1

您应该看到:

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;

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  1. 输出将根据您使用的数据库,而不同
  2. 结合the app (polls)的名字 自动产生Table names
  3. Primary keys (IDs) 是自动添加的(You can override this, too.)
  4. 按照惯例,Django附加"_id"到外键字段名称(您也可以覆盖它。
  5. 外键关系通过 FOREIGN KEY 约束显式化。这只是告诉PostgreSQL在事务结束前不强制执行外键。
  6. 它是根据您正在使用的数据库量身定制的,因此可以自动为您处理特定于数据库的字段类型,如auto_increment(MySQL),serial(PostgreSQL)或(SQLite)。引用字段名称也是如此 - 例如,使用双引号或单引号。
  7. 该sqlmigrate命令实际上并不在数据库上运行迁移 - 它只是将其打印到屏幕上,以便您可以看到SQL Django认为需要什么。

Now, run migrate 再次在数据库中创建这些model tables

$ python manage.py migrate

 
 
  • 1

迁移功能非常强大,您可以在开发项目时随时更改模型,而无需删除数据库或表并创建新数据库 - 它专门用于实时升级数据库,而不会丢失数据。

现在,请记住进行模型更改的三步指南:

  1. 更改模型(in models.py)。
  2. 运行以创建这些更改的迁移***python manage.py makemigrations***
  3. 运行以将这些更改应用于数据库。python manage.py migrate

Playing with the API¶

跳进交互式Python shell并使用Django的免费API。调用Python shell,

$ python manage.py shell

 
 
  • 1

in the shell, 可以开发数据库的API:

创建管理员用户¶

Username: admin
Email address: admin@example.com
Password: 12345678

Introducing the Django Admin¶

Django完全自动化为模型创建管理界面。
管理员不打算由网站访问者使用。它适用于网站管理员。

创建管理员用户¶

首先,我们需要创建一个可以登录管理站点的用户

$ python manage.py createsuperuser

 
 
  • 1

输入所需的用户名,然后按Enter键。

然后,系统将提示您输入所需的电子邮件地址:

最后一步是输入密码。系统会要求您输入两次密码,第二次输入密码作为第一次确认。

启动开发服务器¶

Django管理站点默认激活。让我们启动开发服务器并进行探索。
如果服务器没有运行,请启动它:

$ python manage.py runserver

 
 
  • 1

打开Web浏览器并转到本地域的“/ admin /” - 例如,http://127.0.0.1:8000 / admin /

进入管理站点¶

现在,尝试使用您在上一步中创建的超级用户帐户登录。你应该看到Django管理员索引页面

使管理中的polls应用可修改¶

但是我们的投票应用程序在哪里?它不会显示在管理员索引页面上。

只需做一件事:我们需要告诉管理员Question 对象有一个管理界面。
为此,请打开该polls/admin.py 文件,然后将其编辑为如下所示:

polls/admin.py¶
from django.contrib import admin
from .models import Question

admin.site.register(Question)

  • 1
  • 2
  • 3
  • 4
  • 5

探索免费的管理功能¶

单击“问题”。您将进入“更改列表”页面以查询问题

注意的事项:

  1. 表单是从Question模型自动生成的。
  2. 不同的模型字段类型(DateTimeField, CharField)对应于相应的HTML输入窗口小部件。每种类型的字段都知道如何在Django管理员中显示自己。
  3. 每个都DateTimeField获得免费的JavaScript快捷方式。日期获得“今日”快捷方式和日历弹出窗口,时间获得“现在”快捷方式和方便的弹出窗口,列出常用的输入时间。

OK

已经了解了,更改模型,创建数据,修改模型API,熟悉管理站点
接下来,第3部分,如何在APP中,添加更多视图。

                                </div>
            <link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-b6c3c6d139.css" rel="stylesheet">
                                            <div class="more-toolbox">
            <div class="left-toolbox">
                <ul class="toolbox-list">
                    
                    <li class="tool-item tool-active is-like "><a href="javascript:;"><svg class="icon" aria-hidden="true">
                        <use xlink:href="#csdnc-thumbsup"></use>
                    </svg><span class="name">点赞</span>
                    <span class="count"></span>
                    </a></li>
                    <li class="tool-item tool-active is-collection "><a href="javascript:;" data-report-click="{&quot;mod&quot;:&quot;popu_824&quot;}"><svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-csdnc-Collection-G"></use>
                    </svg><span class="name">收藏</span></a></li>
                    <li class="tool-item tool-active is-share"><a href="javascript:;"><svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-csdnc-fenxiang"></use>
                    </svg>分享</a></li>
                    <!--打赏开始-->
                                            <!--打赏结束-->
                                            <li class="tool-item tool-more">
                        <a>
                        <svg t="1575545411852" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5717" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M179.176 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5718"></path><path d="M509.684 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5719"></path><path d="M846.175 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5720"></path></svg>
                        </a>
                        <ul class="more-box">
                            <li class="item"><a class="article-report">文章举报</a></li>
                        </ul>
                    </li>
                                        </ul>
            </div>
                        </div>
        <div class="person-messagebox">
            <div class="left-message"><a href="https://blog.csdn.net/qq1376725255">
                <img src="https://profile.csdnimg.cn/1/1/9/3_qq1376725255" class="avatar_pic" username="qq1376725255">
                                        <img src="https://g.csdnimg.cn/static/user-reg-year/2x/5.png" class="user-years">
                                </a></div>
            <div class="middle-message">
                                    <div class="title"><span class="tit"><a href="https://blog.csdn.net/qq1376725255" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;}" target="_blank">帅金毛</a></span>
                                        </div>
                <div class="text"><span>发布了82 篇原创文章</span> · <span>获赞 13</span> · <span>访问量 3万+</span></div>
            </div>
                            <div class="right-message">
                                        <a href="https://im.csdn.net/im/main.html?userName=qq1376725255" target="_blank" class="btn btn-sm btn-red-hollow bt-button personal-letter">私信
                    </a>
                                                        <a class="btn btn-sm  bt-button personal-watch" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;}">关注</a>
                                </div>
                        </div>
                </div>
</article>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值