1、安裝
Python安裝:pip install django
安裝完成後會在Python的安裝目錄下的"/Scripts"下面出現兩個新文件,分別是django-admin的應用程序文件和JetBrains Pycharm文件(django-admin.exe,django-admin.py)。這兩個文件是用來實現自動建立目錄的。css
2、建立Django工程
語法:django-admin startproject 【工程名稱】
在cmd中,執行django-admin.exe startproject mysite命令,會自動在當前目錄下生成一個mysite文件夾。
格式以下:
mysite
- mysite # 對整個程序進行配置
- __init__.py
- settings.py # 配置文件
- urls.py # URL對應關係
- wsgi.py # 遵循WSIG規範,通常不使用原生的,而是本身配置uwsgi + nginx
- manage.py # 管理Django程序。
運行Django功能的經常使用命令:
python manage.py runserver 127.0.0.1:8001
python manage.py
python manage.py startapp appname
python manage.py syncdb
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuserhtml
支持WSGI規範的server模塊:python
1 server_names = { 2 'cgi': CGIServer, 3 'flup': FlupFCGIServer, 4 'wsgiref': WSGIRefServer, 5 'waitress': WaitressServer, 6 'cherrypy': CherryPyServer, 7 'paste': PasteServer, 8 'fapws3': FapwsServer, 9 'tornado': TornadoServer, 10 'gae': AppEngineServer, 11 'twisted': TwistedServer, 12 'diesel': DieselServer, 13 'meinheld': MeinheldServer, 14 'gunicorn': GunicornServer, 15 'eventlet': EventletServer, 16 'gevent': GeventServer, 17 'geventSocketIO':GeventSocketIOServer, 18 'rocket': RocketServer, 19 'bjoern' : BjoernServer, 20 'auto': AutoServer, 21 }
工程架構:jquery
項目名稱
- 項目名
- 配置
- 主站 app
- 後臺管理 app
# 建立app:
語法:python manage.py startapp appname
- python manage.py startapp cmdb
- python manage.py startapp openstack
# 查看app目錄:
- migrations 數據修改表結構的操做記錄
- __init__.py
- __init__.py
- admin.py Django爲咱們提供的後臺管理
- apps.py 配置當前app
- models.py ORM,寫指定的類 經過命令能夠建立數據庫結構
- tests.py 單元測試
- views.py 業務代碼
nginx
3、建立項目後上部署執行順序
一、配置模板的路徑數據庫
1 TEMPLATES = [ 2 { 3 'BACKEND': 'django.template.backends.django.DjangoTemplates', 4 'DIRS': [os.path.join(BASE_DIR, 'templates')] 5 , 6 'APP_DIRS': True, 7 'OPTIONS': { 8 'context_processors': [ 9 'django.template.context_processors.debug', 10 'django.template.context_processors.request', 11 'django.contrib.auth.context_processors.auth', 12 'django.contrib.messages.context_processors.messages', 13 ], 14 }, 15 }, 16 ]
二、配置靜態目錄django
static爲默認靜態文件目錄名。session
settings.py文件中增長下面代碼:架構
1 STATICFILES_DIRS=( 2 os.path.join(BASE_DIR,'static'), 3 )
三、在html中引用靜態目錄css文件,和js文件app
<link rel="stylesheet" href="/static/commons.css" />
<script src="/static/jquery.min.js"></script>
4、上述內容整理
1. 建立Django工程
django-admin startproject 工程名
2. 建立APP
cd 工程名
python manage.py startapp cmdb
三、靜態文件
project.settings.py
STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), )
四、模板路徑
'DIRS': [os.path.join(BASE_DIR, 'templates')],
五、settings中
MIDDLERWARE
1 # 註釋 csrf,避免跨站請求僞造報錯 2 MIDDLEWARE = [ 3 'django.middleware.security.SecurityMiddleware', 4 'django.contrib.sessions.middleware.SessionMiddleware', 5 'django.middleware.common.CommonMiddleware', 6 # 'django.middleware.csrf.CsrfViewMiddleware', 7 'django.contrib.auth.middleware.AuthenticationMiddleware', 8 'django.contrib.messages.middleware.MessageMiddleware', 9 'django.middleware.clickjacking.XFrameOptionsMiddleware', 10 ] 11 ps:提交的method爲post時,須要註釋csrf;method=get時,csrf不受影響。
六、定義路由規則
url.py
"login" --> 函數名
1 urlpatterns = [ 2 url(r'^admin/', admin.site.urls), 3 url(r'^h.html', views.home), 4 url(r'^login',views.login), 5 ]
七、定義視圖函數
app下views.py
def func(request): # request.method #返回值結果: GET 或 POST(最經常使用考慮的兩種提交方式,其餘有:PUT,DELETE,HEAD,OPTION...) # http://127.0.0.1:8009/home?nid=123&name=alex # request.GET.get('',None) # 獲取GET請求發來的而數據 # request.POST.get('',None) # 獲取POST請求發來的而數據 # return HttpResponse("字符串") # 返回字符串數據 # return render(request, "HTML模板的路徑") # 打開並返回模板數據 # return redirect('/只能填URL') # 轉至/URL
八、模板渲染
特殊的模板語言
1 from django.shortcuts import render 2 3 # Create your views here. 4 from django.shortcuts import HttpResponse 5 from django.shortcuts import render 6 from django.shortcuts import redirect 7 def home(request): 8 return HttpResponse('<h1>Hello cmdb!<h1>') 9 10 def login(request): 11 # request包含了用戶提交的全部信息 12 # 獲取用戶提交方法request.method 13 14 error_msg='' 15 if request.method=='POST': 16 # 獲取用戶經過POST提交過來的數據 17 user=request.POST.get('user',None) 18 pwd=request.POST.get('pwd',None) 19 if user=='root' and pwd=='123': 20 # 去跳轉到 21 return redirect('/home') 22 else: 23 #用戶名密碼不匹配 24 error_msg='用戶名或密碼錯誤' 25 return render(request, 'login.html', {'error_msg': error_msg}) 26 27 else: 28 return render(request,'login.html') 29 30 31 USER_LIST=[ 32 {'username':'alex','email':'123@163.com','gender':'male'}, 33 ] 34 35 def home(request): 36 if request.method=='POST': 37 u=request.POST.get('username',None) 38 e = request.POST.get('email', None) 39 g = request.POST.get('gender', None) 40 temp={'username':u,'email':e,'gender':g} 41 USER_LIST.append(temp) 42 return render(request,'home.html',{'user_list':USER_LIST})
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body style="margin:0"> 8 <div style="height:48px;background-color:#dddddd" class="pg-header"></div> 9 <div> 10 <form action="/home" method="POST"> 11 <input type="text" name="username" placeholder="用戶名"/> 12 <input type="text" name="email" placeholder="郵箱"/> 13 <input type="text" name="gender" placeholder="性別"/> 14 <input type="submit" value="添加"/> 15 16 </form> 17 </div> 18 <div> 19 <table> 20 {% for row in user_list %} 21 22 <tr> 23 <td>{{ row.username }}</td> 24 <td>{{ row.email }}</td> 25 <td>{{ row.gender }}</td> 26 </tr> 27 {% endfor %} 28 </table> 29 </div> 30 31 </body> 32 </html>
{{ 變量名 }}
for循環和if條件語句嵌套:
{% for row in user_list %}
{% if row == "alex" %}
<li>{{ row }}</li>
{% endif %}
{% endfor %}
索引:
{{ user_dict.k2 }}
九、Django的請求生命週期
客戶端向服務端發送請求-> 請求到達路由系統,經路由系統進行路由匹配(URL對應關係(匹配)) -> 匹配成功,找到對應視圖函數 -> 執行視圖函數,返回用戶字符串
客戶端向服務端發送請求-> 請求到達路由系統,經路由系統進行路由匹配(URL對應關係(匹配)) -> 匹配成功,找到對應視圖函數 -> 執行視圖函數,打開一個HTML文件,讀取內容,返回內容