2012年5月19日

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:\Python25\Lib\site-packages\django\bin2.寻找目录中是否存在django-admin.py 程式,一般会存在Django所安装的目录中,如上所述。3.建立专案,进入windows command line的模式,假设我们所要建立的专案名称为mysite且目录位于C:\中,则必须先切换到c:\,接着输入python C:\Python25\Lib\site-packages\django\bin\django-admin.py startproject mysite4.C槽则会产生一个mysite的目录,目录中则会存在四个档:





mysite/
    __init__.py
    manage.py
    settings.py
    urls.py
此四个档案的说明请参考Writing your first Django app, part 1



三. 启动网页伺服器1.切换到mysite所在的目录。 ex: cd c:\mysite2.执行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 startapp polls

之后django资料库中会产生一些系统预设的资料表。
五.建立应用程式(application)在每个专案(Project)底下我们可以建立很多应用程式(app),在此我们以polls app为例,在python中若要参考此应用程式其使用方式为mysite.polls1.首先我们要先建立此应用程式polls app,切换到mysite目录下执行python manage.py startapp polls执行完成后,会产生一个polls的目录及一些预设的档案。


polls/
    __init__.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',
    'mysite.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.环境设定在专案执行前可透过下列方式来对系统执行环境进行设定#windowsset PYTHONPATH=C:\python25\;C:\mysite\;set DJANGO_SETTINGS_MODULE=settings#linuxPYTHONPATH="/django/mysite/:/django/"DJANGO_SETTINGS_MODULE="settinexport PYTHONPATH DJANGO_SETTINGS_MODULE2.进入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()

没有评论:

发表评论

BlogAD