1. 程式人生 > >【Mac系統 + Python + Django】之搭建第一個Demo

【Mac系統 + Python + Django】之搭建第一個Demo

versions 打開 配置 onf demo -s 進入 127.0.0.1 seq

一、首先,用pip安裝Django

# 安裝命令
pip install django==1.10.3

安裝路徑為:

/Users/zhan/.pyenv/versions/3.6.1/lib/python3.6/site-packages/django

二、創建項目與應用

安裝完成之後,會多出一個django-admin的文件,此文件會提供Django所有的命令。

查看django-admin文件的路徑,命令:

which django-admin

django-admin路徑為:

/Users/zhan/.pyenv/versions/3.6.1/bin/django-admin

輸入命令,查看django命令:

# 輸入
django-admin # 如下 Type ‘django-admin help <subcommand>‘ for help on a specific subcommand. Available subcommands: [django] check compilemessages createcachetable dbshell diffsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate runserver sendtestemail shell showmigrations sqlflush sqlmigrate sqlsequencereset squashmigrations startapp startproject test testserver

cd 到需要創建項目的目錄下,並使用startproject來創建項目,命令為:

# 進入需要創建的目錄下
cd xxx/xxx/Demo/

# 創建項目
django-admin startproject guest

創建後如圖所示:

技術分享圖片

命令行再輸入:

# 進入guest項目
cd guest

# 查看manage所提供的命令
python manage.py

Type ‘manage.py help <subcommand>‘ for help on a specific subcommand.

Available subcommands:

[auth]

changepassword
createsuperuser

[django]
check
compilemessages
createcachetable
dbshell
diffsettings
dumpdata
flush
inspectdb
loaddata
makemessages
makemigrations
migrate
sendtestemail
shell
showmigrations
sqlflush
sqlmigrate
sqlsequencereset
squashmigrations
startapp
startproject
test
testserver

[sessions]
clearsessions

[staticfiles]
collectstatic
findstatic
runserver

再接著創建sign應用,命令:

# 創建應用
python manage.py startapp sign

如圖所示:

技術分享圖片

三、運行Django

通過輸入命令:

# 運行服務
python manage.py runserver


Performing system checks...

System check identified no issues (0 silenced).

You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run ‘python manage.py migrate‘ to apply them.

October 11, 2018 - 07:21:03
Django version 1.10.3, using settings ‘guest.settings‘
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

瀏覽器打開地址:http://127.0.0.1:8000/

技術分享圖片

說明Django已經在運行了。

如果你的8080端口被占用了,可以使用指定的端口,命令為:

python manage.py runserver 127.0.0.1:8001

如圖所示:

技術分享圖片

四、Hello World

如何在web頁面打印“Hello World”

首先,需要配置一下文件guest/settings.py,將sign應用添加到項目中。

技術分享圖片

其次,打開urls.py文件,添加路徑如下:

from django.conf.urls import url
from django.contrib import admin
from sign import views   # 導入sign的views文件

urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(r^index/$, views.index),  # 添加index/路徑配置
]

最後在views.py中添加index方法:

from django.shortcuts import render
from django.http import HttpResponse    # 引用HttpResponse類
# Create your views here. 
def index(request):
  return HttpResponse("Hello World!!")

再返回到瀏覽器刷新頁面:

技術分享圖片

第一個Demo完成啦!

【Mac系統 + Python + Django】之搭建第一個Demo