用pip安裝Django
pip install django
建立一個叫「demo”的新project
django-admin startproject demo
把web server跑起來
cd demo
python manage.py runserver
然後打開點開 http://127.0.0.1:8000,應該能看到以下頁面,說明建立成功了
如果不想用默認的8000,想換一個端口(port),比如1234,可以這樣啟動
python manage.py runserver 1234
建立一個叫「myapp「的app
python manage.py startapp myapp
這個時候,demo目錄下的內容如下
編輯myapp下面的views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(response):
return HttpResponse("<h1>Hello from my first Django app</h1>")
在myapp下面新建一個叫 urls.py 的文件
myapp/urls.py 寫入如下內容
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
]
注意 urlpatterns 變量名一定不能寫錯,否則會出現以下錯誤
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'myapp.urls' from '/<project path>/demo/myapp/urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
打開demo/urls.py
demo/urls.py 修改為如下
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("myapp.urls")),
]
瀏覽器里刷新 django 網頁
到這裡,我們就用Django做好一個能用的web app了。這裡每個網頁views.py裏面用HttpResponse輸出html,這肯定是不scalable。而且這樣很能加入javascript/css。解決辦事是我們需要html template。下一片文章將會介紹在Django html template。