[Django v2.0 (2)] 建立第一個App

天道酬勤
Sep 9, 2018 · 3 min read

[Django v2.0 (2)] 建立第一個App

簡介

既上一篇[Django v2.0 (1)]安裝與開啟第一個Server這一次要在Server底下,建立一個投票功能的Application.

Django為一個framework語言,Django建立出的project底下可以執行多個Apps.

舉個例子, Facebook同時具備多個apps,可以供使用者發佈文章、投票、打卡、聊天等等。

對於開發者而言,一個project可以加入多項的apps功能,同時,也能夠將app的功能移植到其他的project之中。


實作

打開命令提式字元(cmd)

Step 1 : 建立名為polls的app

python manage.py startapp polls

在根目錄底下會出現名為polls的資料夾

mysite-|--manage.py
/--mysite----|--__init__.py
|--settings.py
|--urls.py
|--wsgi.py
/--polls-----|__init__.py
|--admin.py
|--apps.py
|--models.py
|--tests.py
|--views.py
/--migrations---|__init__.py

Step 2 : 編輯投票頁面(polls)的顯示內容

1. 編輯polls/view.py

2. 呼叫view.index時,即顯示” Hello, world. You’re at the polls index.”

Step 3 : 建立與polls/views.py的url連結

1. 編輯polls/urls.py

2. from . import views 從上一層的目錄引用views物件

若想要進一步了解import這個功能,可參考以下兩篇文章

3. path(‘ ’, view.index, name=’index’)

http://127.0.0.1/polls/
|----當polls後的url為空時,呼叫view.index

Step 4 : 設定mysite.py的url連結

編輯mysite/urls.py

http://127.0.0.1/polls/
|----當mysite後的url為polls,呼叫polls/urls.py

Step 5: 開啟Server

python manage.py runserver

Step 6: 進入http://127.0.0.1/polls/

成功建立一個App,並進入這個頁面,接下來的教學,會對這個頁面進行更多編輯!!!


參考資料

Django Documentation Release 2.1.2.dev20180901131607

天道酬勤

Written by

藉由這個Blog紀錄與分享自己學習的過程

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade