Django建立第一個專案

環境python3版本

pip install Django

檢查是否成功安裝

python -m django --version

建立專案(project)
先cd到要建立專案的資料夾底下

django-admin startproject Hangman

檔案結構

Hangman/
    manage.py
    Hangman/
        __init__.py
        settings.py
        urls.py
        wsgi.py

Hangman/代表專案的根目錄,該名稱可任意變更,manage.py為Django的命令列工具.


開起server

python manage.py runserver [port]

建立應用程式(app)

python manage.py startapp game

在game目錄底下建立 urls.py

建立第一個介面
開啟game/views.py

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello World. You're at the game index")

開啟game/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

開啟Hangman/urls.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('game/', include('game.urls')),
]

再執行

python manage.py runserver

到瀏覽器輸入http://127.0.0.1:8000/game/

留言