Django開發web站點步驟
1、創建Django工程
django-admin startproject 工程名
2、創建App
cd 工程名 python manage.py startapp cmdb
3、靜態文件配置
編輯 project.settings.py,追加以下內容
STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), )
4、模板路徑配置
DIRS ==> (os.path.join(BASE_DIR, ‘templates‘),)
5、settings中,註釋 csrf
MIDDLEWARE_CLASSES = ( #‘django.middleware.csrf.CsrfViewMiddleware‘, )
6、定義路由規則,在url.py中定義用戶訪問的url由哪個函數來處理請求
url.py "login" --> 函數名
7、定義視圖函數,在views.py中定義函數
def func(reuest): # request.method GET/POST # http://127.0.0.1:8000/home?nid=123&name=bob # request.GET.get(‘‘,None) #獲取請求發來的數據 # request.POST.get(‘‘,None) # return HttpResponse("字符串") # return Render(request, ‘HTML模板路徑‘,{"user_list": USER_LIST}) # return redirect(‘只能填URL,例如:/home‘)
8、模板渲染
Django特殊的模板語言,例如:
--變量名取值--
在views.py中定義好變量和對應的值,在template的html頁面中通過{{ var_name }}的方式來取值
def func(request): return render(request,"index.html",{‘current_user‘: "bob"}) index.html <html> <body> <div>{{ current_user }}</div> </body> </html>
--For循環取值--
在views.py中定義好列表和值,在template的html頁面中通過{{ for循環 }}的方式來取值
def func(request): return render(request,"index.html",{ ‘current_user‘: "bob", ‘user_list‘:[‘bob‘,‘aaa‘,‘bbb‘]}) index.html <html> <body> <div>{{ current_user }}</div> <ul> {% for row in user_list %} <li>{{ row }}</li> <% endfor %> </ul> </body> </html>
--索引取值--
在views.py中定義好字典和值,在template的html頁面中通過{{ var_name.key }}的方式來取值
def func(request): return render(request,"index.html",{ ‘current_user‘: "bob", ‘user_list‘: [‘bob‘,‘aaa‘,‘bbb‘], ‘user_dict‘: [‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘] }) index.html <html> <body> <div>{{ current_user }}</div> <a>{{ user_list.1 }}</a> //對於列表直接用索引取值 <a>{{ user_dict.k1 }}</a> //對於字典,要用key取值 <a>{{ user_dict.k2 }}</a> </body> </html>
--條件取值--
{% if %}
{% if %}
{% endif %}
{% else%}
{% else %}
{% endif %}
def func(request): return render(request,"index.html",{ ‘current_user‘: "bob", ‘age‘: 18, ‘user_list‘: [‘bob‘,‘aaa‘,‘bbb‘], ‘user_dict‘: [‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘] }) index.html <html> <body> <div>{{ current_user }}</div> <a>{{ user_list.1 }}</a> //對於列表直接用索引取值 <a>{{ user_dict.k1 }}</a> //對於字典,要用key取值 <a>{{ user_dict.k2 }}</a> {% if age %} <a>有年齡</a> {% if age > 16 %} <a>老男人</a> {% else %} <a>小鮮肉</a> {% endif %} {% else %} <a>無年齡</a> {% endif %} </body> </html>
模板的工作流程:
1、當用戶請求通過url發送請求後,django路由將請求交給視圖函數,
2、然後視圖函數會先去取模板,
3、將模板中有{{ current_user }}這樣的變量與視圖中定義的值進行渲染,渲染後將模板內容轉換成字符串
4、將生成後字符串整體返回給用戶
過濾器
模板過濾器是變量顯示前轉換它們的值的方式,看起來像下面這樣
{{ name|lower }}
這將顯示通過lower過濾器過濾後{{ name }}變量的值,它將文本轉換成小寫
使用(|)管道來申請一個過濾器
過濾器可以串成鏈,即一個過濾器的結果可以傳向下一個,下面是escape文本內容然後把換行轉換成p標簽的習慣用法
{{ my_text|escape|linebreaks }}
更過關於Django模板的資料,請訪問:
http://blog.csdn.net/zhangxinrun/article/details/8095118/
本文出自 “zengestudy” 博客,請務必保留此出處http://zengestudy.blog.51cto.com/1702365/1931369
Django開發web站點步驟