1. å建项ç®
è¿è¡ä¸é¢å½ä»¤å°±å¯ä»¥å建ä¸ä¸ª django 项ç®ï¼é¡¹ç®åç§°å« mysite ï¼
$ django-admin.py startproject mysite
å建åç项ç®ç®å½å¦ä¸ï¼
mysite
âââ manage.py
âââ mysite
âââ __init__.py
âââ settings.py
âââ urls.py
âââ wsgi.py
1 directory, 5 files
说æï¼
__init__.py ï¼è®© Python æ该ç®å½å½æä¸ä¸ªå¼åå
(å³ä¸ç»æ¨¡å)æéçæ件ã è¿æ¯ä¸ä¸ªç©ºæ件ï¼ä¸è¬ä½ ä¸éè¦ä¿®æ¹å®ã
manage.py ï¼ä¸ç§å½ä»¤è¡å·¥å
·ï¼å
è®¸ä½ ä»¥å¤ç§æ¹å¼ä¸è¯¥ Django 项ç®è¿è¡äº¤äºã é®å
¥python manage.py helpï¼çä¸ä¸å®è½åä»ä¹ã ä½ åºå½ä¸éè¦ç¼è¾è¿ä¸ªæ件ï¼å¨è¿ä¸ªç®å½ä¸çæå®çº¯æ¯ä¸ºäºæ¹ä¾¿ã
settings.py ï¼è¯¥ Django 项ç®ç设置æé
ç½®ã
urls.pyï¼Django项ç®çURLè·¯ç±è®¾ç½®ãç®åï¼å®æ¯ç©ºçã
wsgi.pyï¼WSGI web åºç¨æå¡å¨çé
ç½®æ件ãæ´å¤ç»èï¼æ¥ç How to deploy with WSGI
æ¥ä¸æ¥ï¼ä½ å¯ä»¥ä¿®æ¹ settings.py æ件ï¼ä¾å¦ï¼ä¿®æ¹ LANGUAGE_CODEã设置æ¶åº TIME_ZONE
SITE_ID = 1
LANGUAGE_CODE = 'zh_CN'
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = True
ä¸é¢å¼å¯äº [Time zone](
https://docs.djangoproject.com/en/1.7/topics/i18n/timezones/) ç¹æ§ï¼éè¦å®è£
pytzï¼
$ sudo pip install pytz
2. è¿è¡é¡¹ç®
å¨è¿è¡é¡¹ç®ä¹åï¼æ们éè¦å建æ°æ®åºå表ç»æï¼è¿éæ使ç¨çé»è®¤æ°æ®åºï¼
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, contenttypes, auth, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying sessions.0001_initial... OK
ç¶åå¯å¨æå¡ï¼
$ python manage.py runserver
ä½ ä¼çå°ä¸é¢çè¾åºï¼
Performing system checks...
System check identified no issues (0 silenced).
January 28, 2015 - 02:08:33
Django version 1.7.1, using settings 'mysite.settings'
Starting development server at
http://127.0.0.1:8000/Quit the server with CONTROL-C.
è¿å°ä¼å¨ç«¯å£8000å¯å¨ä¸ä¸ªæ¬å°æå¡å¨, 并ä¸åªè½ä»ä½ çè¿å°çµèè¿æ¥å访é®ã æ¢ç¶æå¡å¨å·²ç»è¿è¡èµ·æ¥äºï¼ç°å¨ç¨ç½é¡µæµè§å¨è®¿é®
http://127.0.0.1:8000/ãä½ åºè¯¥å¯ä»¥çå°ä¸ä¸ªä»¤äººèµå¿æ¦ç®çæ·¡èè² Django 欢è¿é¡µé¢å®å¼å§å·¥ä½äºã
ä½ ä¹å¯ä»¥æå®å¯å¨ç«¯å£:
$ python manage.py runserver 8080
以åæå® ipï¼
$ python manage.py runserver 0.0.0.0:8000
3. å建 app
åé¢å建äºä¸ä¸ªé¡¹ç®å¹¶ä¸æåè¿è¡ï¼ç°å¨æ¥å建ä¸ä¸ª appï¼ä¸ä¸ª app ç¸å½äºé¡¹ç®çä¸ä¸ªå模åã
å¨é¡¹ç®ç®å½ä¸å建ä¸ä¸ª appï¼
$ python manage.py startapp polls
å¦ææä½æåï¼ä½ ä¼å¨ mysite æ件夹ä¸çå°å·²ç»å¤äºä¸ä¸ªå« polls çæ件夹ï¼ç®å½ç»æå¦ä¸ï¼
polls
âââ __init__.py
âââ admin.py
âââ migrations
â âââ __init__.py
âââ models.py
âââ tests.py
âââ views.py
1 directory, 6 files
4. å建模å
æ¯ä¸ä¸ª Django Model é½ç»§æ¿èª django.db.models.Model
å¨ Model å½ä¸æ¯ä¸ä¸ªå±æ§ attribute é½ä»£è¡¨ä¸ä¸ª database field
éè¿ Django Model API å¯ä»¥æ§è¡æ°æ®åºçå¢å æ¹æ¥, èä¸éè¦åä¸äºæ°æ®åºçæ¥è¯¢è¯å¥
æå¼ polls æ件夹ä¸ç models.py æ件ãå建两个模åï¼
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
ç¶åå¨ mysite/settings.py ä¸ä¿®æ¹ INSTALLED_APPS æ·»å pollsï¼
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
å¨æ·»å äºæ°ç app ä¹åï¼æ们éè¦è¿è¡ä¸é¢å½ä»¤åè¯ Django ä½ ç模ååäºæ¹åï¼éè¦è¿ç§»æ°æ®åºï¼
$ python manage.py makemigrations polls
ä½ ä¼çå°ä¸é¢çè¾åºæ¥å¿ï¼
Migrations for 'polls':
0001_initial.py:
- Create model Choice
- Create model Question
- Add field question to choice
ä½ å¯ä»¥ä» polls/migrations/0001_initial.py æ¥çè¿ç§»è¯å¥ã
è¿è¡ä¸é¢è¯å¥ï¼ä½ å¯ä»¥æ¥çè¿ç§»ç sql è¯å¥ï¼
$ python manage.py sqlmigrate polls 0001
è¾åºç»æï¼
BEGIN;
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
CREATE TABLE "polls_choice__new" ("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"));
INSERT INTO "polls_choice__new" ("choice_text", "votes", "id") SELECT "choice_text", "votes", "id" FROM "polls_choice";
DROP TABLE "polls_choice";
ALTER TABLE "polls_choice__new" RENAME TO "polls_choice";
CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");
COMMIT;
ä½ å¯ä»¥è¿è¡ä¸é¢å½ä»¤ï¼æ¥æ£æ¥æ°æ®åºæ¯å¦æé®é¢ï¼
$ python manage.py check
å次è¿è¡ä¸é¢çå½ä»¤ï¼æ¥å建æ°æ·»å ç模åï¼
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, contenttypes, polls, auth, sessions
Running migrations:
Applying polls.0001_initial... OK
æ»ç»ä¸ä¸ï¼å½ä¿®æ¹ä¸ä¸ªæ¨¡åæ¶ï¼éè¦å以ä¸å 个æ¥éª¤ï¼
ä¿®æ¹ models.py æ件
è¿è¡ python manage.py makemigrations å建è¿ç§»è¯å¥
è¿è¡ python manage.py migrateï¼å°æ¨¡åçæ¹åè¿ç§»å°æ°æ®åºä¸
ä½ å¯ä»¥é
读 django-admin.py documentationï¼æ¥çæ´å¤ manage.py çç¨æ³ã
å建äºæ¨¡åä¹åï¼æ们å¯ä»¥éè¿ Django æä¾ç API æ¥åæµè¯ãè¿è¡ä¸é¢å½ä»¤å¯ä»¥è¿å
¥å° python shell ç交äºæ¨¡å¼ï¼
$ 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()
[]
# 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()
[<Question: Question object>]
æå°ææç Question æ¶ï¼è¾åºçç»ææ¯ [<Question: Question object>]ï¼æ们å¯ä»¥ä¿®æ¹æ¨¡åç±»ï¼ä½¿å
¶è¾åºæ´ä¸ºææçæè¿°ãä¿®æ¹æ¨¡åç±»ï¼
from django.db import models
class Question(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.question_text
class Choice(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.choice_text
æ¥ä¸æ¥ç»§ç»æµè¯ï¼
>>> from polls.models import Question, Choice
# Make sure our __str__() addition worked.
>>> Question.objects.all()
[<Question: What's up?>]
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
>>> Question.objects.filter(question_text__startswith='What')
[<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)
# 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()
[]
# 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()
[<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)
[<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()
>>>
ä¸é¢è¿é¨åæµè¯ï¼æ¶åå° django orm ç¸å
³çç¥è¯ï¼è¯¦ç»è¯´æå¯ä»¥åè Djangoä¸çORMã
5. 管ç admin
Djangoæä¸ä¸ªä¼ç§çç¹æ§, å
ç½®äºDjango adminåå°ç®¡ççé¢, æ¹ä¾¿ç®¡çè
è¿è¡æ·»å åå é¤ç½ç«çå
容.
æ°å»ºç项ç®ç³»ç»å·²ç»ä¸ºæ们设置好äºåå°ç®¡çåè½ï¼è§ mysite/settings.pyï¼
INSTALLED_APPS = (
'django.contrib.admin', #é»è®¤æ·»å åå°ç®¡çåè½
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mysite',
)
åæ¶ä¹å·²ç»æ·»å äºè¿å
¥åå°ç®¡çç url, å¯ä»¥å¨ mysite/urls.py ä¸æ¥çï¼
url(r'^admin/', include(admin.site.urls)), #å¯ä»¥ä½¿ç¨è®¾ç½®å¥½çurlè¿å
¥ç½ç«åå°
æ¥ä¸æ¥æ们éè¦å建ä¸ä¸ªç®¡çç¨æ·æ¥ç»å½ admin åå°ç®¡ççé¢ï¼
$ python manage.py createsuperuser
Username (leave blank to use 'june'): admin
Email address:
Password:
Password (again):
Superuser created successfully.
æ»ç»
æåï¼æ¥ç项ç®ç®å½ç»æï¼
mysite
âââ db.sqlite3
âââ manage.py
âââ mysite
â âââ __init__.py
â âââ settings.py
â âââ urls.py
â âââ wsgi.py
âââ polls
â âââ __init__.py
â âââ admin.py
â âââ migrations
â â âââ 0001_initial.py
â â âââ __init__.py
â âââ models.py
â âââ templates
â â âââ polls
â â âââ detail.html
â â âââ index.html
â â âââ results.html
â âââ tests.py
â âââ urls.py
â âââ views.py
âââ templates
âââ admin
âââ base_site.htm
éè¿ä¸é¢çä»ç»ï¼å¯¹ django çå®è£
ãè¿è¡ä»¥åå¦ä½åå»ºè§ å¾å模åæäºä¸ä¸ªæ¸
æ°ç认è¯ï¼æ¥ä¸æ¥å°±å¯ä»¥æ·±å
¥çå¦ä¹ django çèªå¨åæµè¯ãæä¹
åãä¸é´ä»¶ãå½ é
åçç¥è¯ã