- 建立虛擬環境
安裝virtualenv:pip install virtualenv
可能出現問題:
ImportError: cannot import name 'main'
python提示AttributeError:
'NoneType' object has no attribute 'append'
解決方法: pip install https://github.com/pyinstaller/pyinstaller/tarball/develop
- 創建虛擬環境下的項目目錄
virtualenv image
- 激活
進入到new-env目錄下進入到scripts文件夾下,windows下dir可以查看有什麼文件,運行activate
activate
-
創建項目
django-admin startproject dj01
如果出現問題–>到這裏
結構如下-》
dj01/ --項目根目錄是一個容器
manage.py 一個命令行實用程序,可以讓你與這個Django項目以不同的方式進行交互
dj01/ 實際Python包爲您的項目
__init__.py 一個空文件,告訴Python這個目錄應該考慮一個Python包
settings.py Django projec配置
urls.py Django projec URL聲明
wsgi.py WSGI-compatible web服務器的一個入口點爲您的項目
運行以下命令(默認8000端口):
python manage.py runserver
或 python manage.py runserver 8080
結果:
-
創建一個名未Polls的app
python manage.py startapp polls
項目結構如下:
-
配置數據庫
dj01/settings.py 修改如下字段信息:
default
項目以匹配您的數據庫連接設置
ENGINE
可以是 [‘django.db.backends.sqlite3’, ‘django.db.backends.postgresql’, ‘django.db.backends.mysql’, or ‘django.db.backends.oracle’]中的一個. 或者其他(這個類似於java中的數據驅動)
NAME
數據庫名 ( sqlite3 使用 os.path.join(BASE_DIR, ‘db.sqlite3’),)
USER
數據庫用戶名
PASSWORD
數據庫密碼
HOST
數據庫主機地址 -
INSTALLED_APPS
文件底部的 INSTALLED_APPS 設置。它保存了當前 Django 實例已激活 的所有 Django 應用。每個應用可以被多個項目使用,而且你可以打包和分發給其他人在他們的項目中使用。
django.contrib.auth – 身份驗證系統。
django.contrib.contenttypes – 內容類型框架。
django.contrib.sessions – session 框架。
django.contrib.sites – 網站管理框架。
django.contrib.messages – 消息框架。
django.contrib.staticfiles – 靜態文件管理框架。
python manage.py migrate
該命令參照settings.py 文件 `INSTALLED_APPS` 所配置的數據庫中創建必要的數據庫表。每創建一個數據庫表你都會看到一條消息,接着你會看到一個提示詢問你是否想要在身份驗證系統內創建個超級用戶。
- 創建models
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):
# ForeignKey
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
- 將polls 加到dj01/settings.py/INSTALLED_APPS 中
執行以下命令:將已經改變的models告訴django,讓Django知道你想要更新已存在視圖。
python manage.py makemigrations polls
執行結果-
Migrations for 'polls':
polls/migrations/0001_initial.py:
- Create model Choice
- Create model Question
- Add field question to choice
然後執行以下命令,我們將看到數據庫表的生成,以及詳細的sql語句。
python manage.py sqlmigrate polls 0001
BEGIN;
--
-- Create model Choice
--
CREATE TABLE "polls_choice" (
"id" serial NOT NULL PRIMARY KEY,
"choice_text" varchar(200) NOT NULL,
"votes" integer NOT NULL
);
--
-- Create model Question
--
CREATE TABLE "polls_question" (
"id" serial NOT NULL PRIMARY KEY,
"question_text" varchar(200) NOT NULL,
"pub_date" timestamp with time zone NOT NULL
);
--
-- Add field question to choice
--
ALTER TABLE "polls_choice" ADD COLUMN "question_id" integer NOT NULL;
ALTER TABLE "polls_choice" ALTER COLUMN "question_id" DROP DEFAULT;
CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");
ALTER TABLE "polls_choice"
ADD CONSTRAINT "polls_choice_question_id_246c99a640fbbd72_fk_polls_question_id"
FOREIGN KEY ("question_id")
REFERENCES "polls_question" ("id")
DEFERRABLE INITIALLY DEFERRED;
COMMIT;
運行以下命令爲model創建數據表
python manage.py migrate
-
Shell API
在manage.py同目錄下執行,python manage.py shell
進入到shell命令界面,
可進行model操作。# Import the model classes we just wrote. >>> from polls.models import Question, Choice # 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>]>
-
Django Admin
創建超級管理員
-
執行第一個命令,根據提示完成超級管理員的創建
python manage.py createsuperuser
執行以下命令,啓動項目
python manage.py runserver
然後在在瀏覽器訪問127.0.0.1:8000(根據自己設置的ip和端口訪問),將出現以下頁面
輸入上一步驟創建的用戶名和密碼進入以下頁面。
首次進入頁面不存在POLLs 標籤,需要admin.py中加入以下代碼,即可刷新頁面即可看到POLLS標籤欄。
admin.site.register(Poll)