標籤:django開發的步驟
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>
模板的工作流程:
過濾器
模板過濾器是變數顯示前轉換它們的值的方式,看起來像下面這樣
{{ 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網站步驟