1.創建工程
$ django-admin startproject mysite
2.目錄結構
運行:
$ python manage.py runserver
在瀏覽器中輸入:127.0.0.1:8000
看到如下界面,說明成功
3.django-admin工具
使用:django-admin help
查看命令:
$ django-admin help
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
Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.).
4.新建一個App
4.1創建app
$ python manage.py startapp helloapp
$ cd helloapp
$ ll
total 5
-rw-r--r-- 1 PrinceTeng 197121 0 2月 16 16:45 __init__.py
-rw-r--r-- 1 PrinceTeng 197121 66 2月 16 16:45 admin.py
-rw-r--r-- 1 PrinceTeng 197121 96 2月 16 16:45 apps.py
drwxr-xr-x 1 PrinceTeng 197121 0 2月 16 16:45 migrations/
-rw-r--r-- 1 PrinceTeng 197121 60 2月 16 16:45 models.py
-rw-r--r-- 1 PrinceTeng 197121 63 2月 16 16:45 tests.py
-rw-r--r-- 1 PrinceTeng 197121 66 2月 16 16:45 views.py
4.2 修改應用目錄下的views.py
from django.shortcuts import render
from django.http import HttpResponse #增加
# Create your views here.
def hello(request):
return HttpResponse("hello, i am coming")
4.3 修改mysite子目錄下的urls.py
from django.contrib import admin
from django.urls import path
from helloapp import views
urlpatterns = [
path('index/', views.hello),
path('admin/', admin.site.urls),
]
path函數的第一個參數爲url,第二個參數是處理這個url所使用的函數。
4.4 運行
命令行輸入:
$ python manage.py runserver
在瀏覽器輸入地址:http://127.0.0.1:8000/index/
返回內容:
成功!
5.總結
1.新建工程:django-admin startproject [projectname]
2.新建App:python manage.py startapp [appname]
3.修改projectname/appname/views.py
,增加url處理函數
4.修改projectname/projectname/urls.py
,增加url與處理函數的關聯
5.運行服務器:python manage.py runserver
6.瀏覽器輸入url測試