Writing your first Django app, part 2

官方教程-Part2

數據庫設置

安裝數據庫
mysite/settings.py

SQLite

DATABASES = {
    'default': {
        'ENGINE':'django.db.backends.sqlite3',
        'NAME': 'mydatabase',
    }
}

MySQL/Oracle/PostgreSQL

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

安裝應用

mysite/settings.py

默認情況下,INSTALLED_APPS包含以下應用程序,所有這些應用程序都與Django一起提供:

  • django.contrib.admin - 管理網站。你會很快使用它。
  • django.contrib.auth - 認證系統。
  • django.contrib.contenttypes - 內容類型的框架。
  • django.contrib.sessions - 會話框架
  • django.contrib.messages - 消息框架。
  • django.contrib.staticfiles - 管理靜態文件的框架。

創建數據庫

# directory: mysite/manage.py
$ python manage.py migrate

創建models

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)

安裝應用

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

將polls/models.py 中的類轉換成統一格式,爲生成數據庫中的表做準備

polls/models.py -格式化-> polls/migration/number_comment.py

$ python manage.py makemigrations polls

會在polls/migrations/生成如下類似文件

2017/06/17  20:17             1,268 0001_initial.py
2017/06/17  20:17               454 0002_choice_test.py
2017/06/17  20:17               401 0003_remove_choice_test.py
2017/06/17  20:17               447 0004_auto_20170617_1756.py
2017/06/17  20:17               447 0005_auto_20170617_1757.py

查看格式化後的文件將運行什麼SQL

$ python manage.py sqlmigrate polls 0001

生成的文件,(migrate)運行以在數據庫中創建這些模型表:

$ python manage.py migrate

要執行的操作:
應用所有遷移:admin,auth,contenttypes,polls,sessions
運行遷移:
渲染模型狀態… DONE
應用polls.0001_initial … OK

Created with Raphaël 2.1.0編輯或修改models.py文件makemigrations appmigrate ?預覽yesno
  1. 編輯或修改polls/models.py文件
  2. 將models.py格式化
  3. 執行migrate

進入命令行調試

$ python manage.py shell
>>> from polls.models import Question, Choice   # 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
>>> 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.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>]>

編輯polls/models.py,add __str__() methods to your models

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

編輯polls/models.py,add a custom method

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 >= timezome.now() - datetime.timedelta(days=1)

保存這些更改並重新啓動一個新的Python交互式shell :python manage.py shell

>>> from polls.models import Question, Choice

# 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()

創建超級管理員

$ python manage.py createsuperuser
# 根據提示錄入Username|Password

訪問 http://localhost:9000/admin/

Make the poll app modifiable in the admin

polls.py/admin.py

from django.contrib import admin

from .models import Question

admin.site.register(Question)

重啓服務

$ python manage.py runserver

訪問 http://localhost:9000/admin/

http://localhost:9000/admin/polls/question/add/
注意事項:

  • 表單是從Question模型自動生成的。
  • 不同的模型字段類型(DateTimeField, CharField)對應於適當的HTML輸入小部件。每種類型的字段知道如何在Django管理員中顯示自己。
  • 每個都DateTimeField獲得免費的JavaScript快捷方式。日期獲取“今日”快捷方式和日曆彈出窗口,並且時間獲取“Now”快捷方式和一個方便的彈出窗口,列出常用的時間。

頁面底部提供了幾個選項:

  • 保存 - 保存更改並返回到此類型對象的更改列表頁面。
  • 保存並繼續編輯 - 保存更改並重新加載此對象的管理頁面。
  • 保存並添加另一個 - 保存更改並加載此類型對象的新的空白表單。
  • 刪除 - 顯示刪除確認頁面。
發佈了35 篇原創文章 · 獲贊 7 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章