網頁

Django 學習手冊-如何建立專案(1) Tutorial Part 1

Django 學習手冊-如何建立專案(1)

Tutorial Part 1

一.先前準備條件:

1.假設您已安裝python 應用程式。

2.假設您已安裝完成django 應用程式。

您可以在python 的執行環境下輸入 "import django" 測試 Django 是否已安裝成功。




二.建立第一個專案(Project)


1.先切換到Django所在的安裝目錄中。在windows的環境中可利用cd的指令。

ex: C:\Python27\Lib\site-packages\django\bin

2.尋找目錄中是否存在 django-admin.py 程式,一般會存在Django所安裝的目錄中,如上所述。

3.建立專案,進入windows command line的模式,假設我們所要建立的專案名稱為mysite且目錄位於C:\中,則必須先切換到c:\,接著輸入

python C:\Python27\Lib\site-packages\django\bin\django-admin.py startproject mysite

4.C槽則會產生一個mysite的目錄,目錄中則會存在一個mysite的目錄,其內容如下:

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

此四個檔案的說明請參考Writing your first Django app, part 1



三. 啟動網頁伺服器


1.切換到mysite所在的目錄。ex: cd c:\mysite

2.執行python manage.py runserver 則會出現下面畫面。


Validating models...
0 errors found.

Django version 1.0, using settings 'mysite.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

3.接著開啟瀏覽器,在網址列輸入http://localhost:8000/ 或 http://127.0.0.1:8000/ ,當有出現"Wellcome to Django" 網頁時代表網站伺服器可正常運作

4. 當你需要改變port number時,可以執行 python manage.py runserver 8080 來進行變更。

5.若需要切換為public IP時可以執行 python manage.py runserver XXX.XXX.XXX.XXX:8000 來進行變更。



四.資料庫的建立與連結設定


1.首先必須在mysql資料庫中建立一個名為 django的資料庫,建議資料庫預設字型為utf-8,執行的指令為

CREATE DATABASE `django` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

2.修改mysite目錄中的 settings.py檔。設定的項目如下:

DATABASE_ENGINE = 'mysql' #為所使用的資料庫軟體
DATABASE_NAME = 'django' #為所設定的資料庫名稱,此資料庫必須先行建立
DATABASE_USER = 'user' # 登入資料庫的使用者名稱
DATABASE_PASSWORD = '12345' # 登入資料庫的密碼
DATABASE_HOST = '' # 若為本機localhost則不須輸入
DATABASE_PORT = '' # 預設為空字串

3.切換至mysite目錄中來進行與資料庫的同步連結,執行指令為:

$ python manage.py syncdb
執行之後,django資料庫中會產生一些系統預設的資料表。



五.建立應用程式(application)


在每個專案(Project)底下我們可以建立很多應用程式(app),在此我們以polls app為例,在python中若要參考此應用程式其使用方式為 mysite.polls

1.首先我們要先建立此應用程式polls app,切換到mysite目錄下執行

python manage.py startapp polls

執行完成後,會產生一個polls的目錄及一些預設的檔案。
polls/
    __init__.py
    admin.py
    models.py
    tests.py
    views.py


2.建立資料模組(models)

在此階段,我們將建立兩個資料模組polls and choices,修改polls/models.py檔


from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()


3.啟動models
你必須修改mysite目錄中的settings.py檔,在檔案中修改有關 INSTALLED_APPS的區段為


INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'polls'
)


將polls app加入到已安裝完成的apps中,並且可透過 python manage.py sql polls來檢視polls資料表建立的語法(以下為PostgreSQL語法)。



BEGIN;
CREATE TABLE "polls_poll" (
    "id" serial NOT NULL PRIMARY KEY,
    "question" varchar(200) NOT NULL,
    "pub_date" timestamp with time zone NOT NULL
);
CREATE TABLE "polls_choice" (
    "id" serial NOT NULL PRIMARY KEY,
    "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"),
    "choice" varchar(200) NOT NULL,
    "votes" integer NOT NULL
);
COMMIT;
4.產生資料表
當檢視資料表建立語法無誤後,實際要產生資料表時,可利用syncdb的方式來處理



python manage.py syncdb




六.Playing with the API


1.環境設定

在專案執行前可透過下列方式來對系統執行環境進行設定

#windows
set PYTHONPATH=C:\python27\;C:\mysite\;
set DJANGO_SETTINGS_MODULE=settings

#linux
PYTHONPATH="/django/mysite/:/django/"
DJANGO_SETTINGS_MODULE="settinexport PYTHONPATH DJANGO_SETTINGS_MODULE

2.進入shell執行環境
我們可以透過下列方式來進入mysite專案的python shell環境執行相關指令



python manage.py shell



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

# No polls are in the system yet.
>>> Poll.objects.all()
[]

# Create a new Poll.
>>> import datetime
>>> p = Poll(question="What's up?", pub_date=datetime.datetime.now())

# Save the object into the database. You have to call save() explicitly.
>>> p.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.
>>> p.id
1

# Access database columns via Python attributes.
>>> p.question
"What's up?"
>>> p.pub_date
datetime.datetime(2007, 7, 15, 12, 00, 53)

# Change values by changing the attributes, then calling save().
>>> p.pub_date = datetime.datetime(2007, 4, 1, 0, 0)
>>> p.save()

# objects.all() displays all the polls in the database.
>>> Poll.objects.all()
[Poll: Poll object]


上列執行Poll.objects.all()時並無法明顯看出Poll物件,我們可以修改polls/models.py檔增加__unicode__() funcgion來改善。



class Poll(models.Model):
    # ...
    def __unicode__(self):
        return self.question

class Choice(models.Model):
    # ...
    def __unicode__(self):
        return self.choice


因此在呼叫物件時則會依你所設定的值來回應,ex:

>>> Poll.objects.all()

[What's up?]

另外我們也可以在model中增加客制化的method


import datetime
# ...
class Poll(models.Model):
    # ...
    def was_published_today(self):
        return self.pub_date.date() == datetime.date.today()


可再重新執行python manage.py shell來進行下列的實作

>>> from mysite.polls.models import Poll, Choice

# Make sure our __unicode__() addition worked.
>>> Poll.objects.all()
[Poll: What's up?]

# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Poll.objects.filter(id=1)
[Poll: What's up?]
>>> Poll.objects.filter(question__startswith='What')
[Poll: What's up?]

# Get the poll whose year is 2007.
>>> Poll.objects.get(pub_date__year=2007)
Poll: What's up?

>>> Poll.objects.get(id=2)
Traceback (most recent call last):
    ...
DoesNotExist: Poll 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 Poll.objects.get(id=1).
>>> Poll.objects.get(pk=1)
Poll: What's up?

# Make sure our custom method worked.
>>> p = Poll.objects.get(pk=1)
>>> p.was_published_today()
False

# Give the Poll 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 poll's choices) which can be accessed via the API.
>>> p = Poll.objects.get(pk=1)

# Display any choices from the related object set -- none so far.
>>> p.choice_set.all()
[]

# Create three choices.
>>> p.choice_set.create(choice='Not much', votes=0)
Choice: Not much
>>> p.choice_set.create(choice='The sky', votes=0)
Choice: The sky
>>> c = p.choice_set.create(choice='Just hacking again', votes=0)

# Choice objects have API access to their related Poll objects.
>>> c.poll
Poll: What's up?

# And vice versa: Poll objects get access to Choice objects.
>>> p.choice_set.all()
[Choice: Not much, Choice: The sky, Choice: Just hacking again]
>>> p.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 poll whose pub_date is in 2007.
>>> Choice.objects.filter(poll__pub_date__year=2007)
[Choice: Not much, Choice: The sky, Choice: Just hacking again]

# Let's delete one of the choices. Use delete() for that.
>>> c = p.choice_set.filter(choice__startswith='Just hacking')
>>> c.delete()