第一个Django App(二)


Database setup 数据库安装


1、mysite/settings.py中,Django 2.0默认配置数据库为sqlite3.


# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


2、mysite/settings.py中,设置TIME_ZONE.

TIME_ZONE = 'UTC'


3、INSTATLLED_APPS保存在该Django例子中所有Django应用的名字。APPS可在多个项目中使用,你可以打包和分发这些应用到其他项目中。

# Application definition


INSTALLED_APPS = [
    'django.contrib.admin',     //admin站点,你将马上使用的。
    'django.contrib.auth',       //身份验证系统
    'django.contrib.contenttypes',//内容类型框架
    'django.contrib.sessions',    //session(会话)框架
    'django.contrib.messages', //消息框架
    'django.contrib.staticfiles',  //管理静态文件的框架
]


生成数据库表


python manage.py migrate


migrate命令查找INSTALLED_APPS设置,并根据mysite的数据库设置(mysite/settings.py中)生成任意必要的数据库表以及跟着APP一起迁移数据库。


python3中如何命令行方式看sqlite3数据库?(待学习补充)


migrate命令仅为mysite/settings.py中INSTALLED_APPS有的apps做迁移。


Creating models 创建模型

创建模型,数据库分层,附加的元数据


在简单的poll app中,创建两个模型:Question 和 Choice。


Question有一个question和一个发布日期。

Choice有两个域:选择的文本和计票结果。

每一个Choice域一个Question关联。


polls/models.py


from django.db import models


# Create your models here.


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)


Activating models 激活模式

给这个app生成数据库模式(CREATE TABLE声明)

为Question和Choice对象生成一个Python可访问的API


但首先我们需要告诉项目polls app安装了。


要在project中包含app,需要在INSTALL_APPS设置中为他的配置类增加引用。PollsConfig类在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',
]


这样,Django知道包含polls app。下面运行另一个命令:

python manage.py makemigrations polls


root@imhqq-Lenovo-H5050:/home/imhqq/share/django_dev/mysite# python manage.py makemigrations polls
Migrations for 'polls':
  polls/migrations/0001_initial.py
    - Create model Choice
    - Create model Question
    - Add field question to choice


通过运行makemigrations,将告诉Django你已经对模式做了一些改动(本例中,生成一个新的模式),这样将改动保存为一个migration(迁移)。


迁移描述的是Django如何保存对模式的改动,迁移仅仅是磁盘上的文件。


polls/migrations/0001_initial.py

# Generated by Django 2.0 on 2017-12-30 06:42


from django.db import migrations, models
import django.db.models.deletion




class Migration(migrations.Migration):


    initial = True


    dependencies = [
    ]


    operations = [
        migrations.CreateModel(
            name='Choice',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('choice_text', models.CharField(max_length=200)),
                ('votes', models.IntegerField(default=0)),
            ],
        ),
        migrations.CreateModel(
            name='Question',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('question_text', models.CharField(max_length=200)),
                ('pub_date', models.DateTimeField(verbose_name='date published')),
            ],
        ),
        migrations.AddField(
            model_name='choice',
            name='question',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question'),
        ),
    ]



迁移设计成人可编辑方式,万一想要手动轻微调整Django是如何改变事情的。


migrate命令用于运行迁移及自动管理数据库架构。


sqlmigrate命令输入需要迁移的名字,返回SQL。


python manage.py sqlmigrate polls 0001


root@imhqq-Lenovo-H5050:/home/imhqq/share/django_dev/mysite# python manage.py sqlmigrate polls 0001
BEGIN;
--
-- Create model Choice
--
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
--
-- Create model Question
--
CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
--
-- Add field question to choice
--
ALTER TABLE "polls_choice" RENAME TO "polls_choice__old";
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id") DEFERRABLE INITIALLY DEFERRED);
INSERT INTO "polls_choice" ("question_id", "id", "choice_text", "votes") SELECT NULL, "id", "choice_text", "votes" FROM "polls_choice__old";
DROP TABLE "polls_choice__old";
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");
COMMIT;


表名通过结合app(polls)名字与模式-question和choice的低阶名称产生。(可重载)

Primary keys(IDs)自动添加(可重载)。

Django附加“_id”到foreign  key域名中(可重载)。


sqlmigration命令不会实际在你的数据库运行迁移,仅仅将此打印到屏幕上。

也可运行python manage.py check.


再次运行migrate,在数据库中生成那些模式表。

root@imhqq-Lenovo-H5050:/home/imhqq/share/django_dev/mysite# python manage.py check
System check identified no issues (0 silenced).


三步阐述模式改变:

1、在models.py中改变模式;

2、运行python manage.py makemigrations来为这些改变生成迁移;

3、运行python manage.py migrate来应用这些改变到数据库。



Playing with the API (玩转API)


绕过manage.py

进入python shell:

python manage.py shell或者输入python


root@imhqq-Lenovo-H5050:/home/imhqq/share/django_dev/mysite# python
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.setup()
Traceback (most recent call last):
  File "", line 1, in
  File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 19, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 56, in __getattr__
    self._setup(name)
  File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 41, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
>>>



编辑Question模式(在polls/models.py文件中),为Question和Choice增加__str__()方法。

polls/models.py




import datetime


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


# Create your models here.


class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text

def was_published_recently(self)://增加自定义方法
return self.pub_date >= timezone_now()-datetime.timedelta(days=1)


class Choice(models.Model):
question = models.ForeignKey(Question,
on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text


给样式添加__str__()方法很重要,不仅处理交互式提示式时自己方便,也

由于对象的表示应用贯穿于Django自动生成的admin.


Django Admin介绍

1、创建一个admin user


root@imhqq-Lenovo-H5050:/home/imhqq/share/django_dev/mysite# python manage.py createsuperuser
Username (leave blank to use 'root'): root
Email address: [email protected]
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
Password:
Password (again):
Superuser created successfully.

2、启动开发服务器


web浏览器中输入

http://127.0.0.1:8000/admin/.


root@imhqq-Lenovo-H5050:/home/imhqq/share/django_dev/mysite# python manage.py runserver
Performing system checks...


System check identified no issues (0 silenced).
December 30, 2017 - 12:55:15
Django version 2.0, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[30/Dec/2017 12:55:18] "GET /polls/ HTTP/1.1" 200 40
[30/Dec/2017 12:55:19] "GET /polls/ HTTP/1.1" 200 40
Not Found: /
[30/Dec/2017 12:55:27] "GET / HTTP/1.1" 404 2027
[30/Dec/2017 12:55:36] "GET /admin/ HTTP/1.1" 302 0
[30/Dec/2017 12:55:36] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1855
[30/Dec/2017 12:55:36] "GET /static/admin/css/login.css HTTP/1.1" 304 0
[30/Dec/2017 12:55:36] "GET /static/admin/css/responsive.css HTTP/1.1" 304 0
[30/Dec/2017 12:55:36] "GET /static/admin/css/base.css HTTP/1.1" 304 0
[30/Dec/2017 12:55:36] "GET /static/admin/css/fonts.css HTTP/1.1" 304 0
[30/Dec/2017 12:55:36] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 304 0
[30/Dec/2017 12:55:36] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 304 0
[30/Dec/2017 12:55:43] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0
[30/Dec/2017 12:55:43] "GET /admin/ HTTP/1.1" 200 2983
[30/Dec/2017 12:55:43] "GET /static/admin/css/dashboard.css HTTP/1.1" 200 412
[30/Dec/2017 12:55:43] "GET /static/admin/img/icon-addlink.svg HTTP/1.1" 200 331
[30/Dec/2017 12:55:43] "GET /static/admin/img/icon-changelink.svg HTTP/1.1" 200 380
[30/Dec/2017 12:55:43] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 304 0
[30/Dec/2017 12:55:50] "GET /admin/auth/group/ HTTP/1.1" 200 3583
[30/Dec/2017 12:55:50] "GET /static/admin/css/changelists.css HTTP/1.1" 200 6170
[30/Dec/2017 12:55:50] "GET /static/admin/js/core.js HTTP/1.1" 200 7134
[30/Dec/2017 12:55:50] "GET /static/admin/js/jquery.init.js HTTP/1.1" 200 363
[30/Dec/2017 12:55:50] "GET /static/admin/js/admin/RelatedObjectLookups.js HTTP/1.1" 200 6897
[30/Dec/2017 12:55:50] "GET /static/admin/js/actions.js HTTP/1.1" 200 6502
[30/Dec/2017 12:55:50] "GET /static/admin/js/prepopulate.js HTTP/1.1" 200 1538
[30/Dec/2017 12:55:50] "GET /admin/jsi18n/ HTTP/1.1" 200 3185
[30/Dec/2017 12:55:50] "GET /static/admin/js/urlify.js HTTP/1.1" 200 8729
[30/Dec/2017 12:55:50] "GET /static/admin/js/vendor/jquery/jquery.js HTTP/1.1" 200 258648
[30/Dec/2017 12:55:50] "GET /static/admin/js/vendor/xregexp/xregexp.js HTTP/1.1" 200 128820
[30/Dec/2017 12:55:50] "GET /static/admin/img/search.svg HTTP/1.1" 200 458
[30/Dec/2017 12:55:50] "GET /static/admin/img/tooltag-add.svg HTTP/1.1" 200 331
[30/Dec/2017 12:55:54] "GET /admin/ HTTP/1.1" 200 2983


3、让admin中的poll app可修改


就做一件事:告诉admin,Question对象有一个admin接口。


polls/admin.py文件修改:


from django.contrib import admin


# Register your models here.
from .models import Question


admin.site.register(Question)


4、Explore the free admin functionally




你可能感兴趣的:(Django学习)