URL配置(URLconf)就像Django 所支撐網站的目錄。它的本質是URL與要爲該URL調用的視圖函數之間的映射表;你就是以這種方式告訴Django,對於客戶端發來的某個URL調用哪一段邏輯代碼對應執行php
1 from django.conf.urls import url 2 3 urlpatterns = [ 4 url(正則表達式, views視圖函數,參數,別名), 5 ]
from django.urls import path,re_path from app01 import views urlpatterns = [ re_path(r'^articles/2003/$', views.special_case_2003), re_path(r'^articles/([0-9]{4})/$', views.year_archive), re_path(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive), re_path(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail), ]
注意:css
^articles
而不是 ^/articles
。
在Python 正則表達式中,命名正則表達式組的語法是(?P<name>pattern)
,其中name
是組的名稱,pattern
是要匹配的模式。html
下面是以上URLconf 使用命名組的重寫:前端
1 from django.urls import path,re_path 2 3 from app01 import views 4 5 urlpatterns = [ 6 re_path(r'^articles/2003/$', views.special_case_2003), 7 re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive), 8 re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive), 9 re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.article_detail), 10 ] 11 #捕獲到的數據都是str類型 12 #視圖函數裏能夠指定默認值 13 14 url('blog/$', views.blog), 15 url('blog/?(?P<num>[0-9]{1})', views.blog), 16 def blog(request,num=1): 17 print(num) 18 return HttpResponse('ok')
Django1.1版本的分發python
from django.conf.urls import url,include 程序員
#主urls from django.urls import path,re_path,include from app01 import views from app01 import urls urlpatterns = [ # re_path(r'^app01/',include('app01.urls')),#行 # re_path(r'^app01/&',include('app01.urls')),#不行 # path('app01/',include('app01.urls')),#行 #path('app01/', include(urls)), ]
from django.urls import path,re_path from app01 import views urlpatterns = [ re_path(r'^test/(?P<year>[0-9]{2})/$',views.url_test), ]
在使用Django 項目時,一個常見的需求是得到URL 的最終形式,以用於嵌入到生成的內容中(視圖中和顯示給用戶的URL等)或者用於處理服務器端的導航(重定向等)。人們強烈但願不要硬編碼這些URL(費力、不可擴展且容易產生錯誤)或者設計一種與URLconf 絕不相關的專門的URL 生成機制,由於這樣容易致使必定程度上產生過時的URL。ajax
在須要URL 的地方,對於不一樣層級,Django 提供不一樣的工具用於URL 反查:正則表達式
from django.urls import reverse()函數
from django.urls import path,re_path from app01 import views urlpatterns = [ re_path(r'^test/(?P<year>[0-9]{2})/(?P<month>[0-9]{2})/$',views.url_test,name='test'), ]
html代碼:數據庫
<a href="{% url 'test' 10 23 %}">哈哈</a> django
from django.shortcuts import render, HttpResponse,redirect,reverse def url_test(request,year,month): print(year) print(month) url=reverse('test',args=(10,20)) print(url) return HttpResponse('ok')
總結:1 在html代碼裏{% url "別名" 參數 參數%}
2 在視圖函數中:
2.1 url=reverse('test')
2.2 url=reverse('test',args=(10,20))
當命名你的URL 模式時,請確保使用的名稱不會與其它應用中名稱衝突。若是你的URL 模式叫作comment
,而另一個應用中也有一個一樣的名稱,當你在模板中使用這個名稱的時候不能保證將插入哪一個URL。在URL 名稱中加上一個前綴,好比應用的名稱,將減小衝突的可能。咱們建議使用myapp-comment
而不是comment
。
命名空間(英語:Namespace)是表示標識符的可見範圍。一個標識符可在多個命名空間中定義,它在不一樣命名空間中的含義是互不相干的。這樣,在一個新的命名空間中可定義任何標識符,它們不會與任何已有的標識符發生衝突,由於已有的定義都處於其它命名空間中。
from django.urls import path,re_path,include urlpatterns = [ path('app01/', include('app01.urls')), path('app02/', include('app02.urls')) ]
from django.urls import path,re_path from app01 import views urlpatterns = [ re_path(r'index/',views.index,name='index'), ]
from django.urls import path, re_path, include from app02 import views urlpatterns = [ re_path(r'index/', views.index,name='index'), ]
def index(request): url=reverse('index') print(url) return HttpResponse('index app01')
def index(request): url=reverse('index') print(url) return HttpResponse('index app02')
這樣都找index,app01和app02找到的都是app02的index
如何處理?在路由分發的時候指定名稱空間
總urls.py在路由分發時,指定名稱空間
path('app01/', include(('app01.urls','app01'))), path('app02/', include(('app02.urls','app02')))
url(r'app01/',include('app01.urls',namespace='app01')), url(r'app02/',include('app02.urls',namespace='app02'))
url(r'app01/',include(('app01.urls','app01'))), url(r'app02/',include(('app02.urls','app02')))
在視圖函數反向解析的時候,指定是那個名稱空間下的
url=reverse('app02:index') print(url) url2=reverse('app01:index') print(url2)
在模版裏:
<a href="{% url 'app02:index'%}">哈哈</a>
Django 視圖層
一個視圖函數,簡稱視圖,是一個簡單的Python 函數,它接受Web請求而且返回Web響應。響應能夠是一張網頁的HTML內容,一個重定向,一個404錯誤,一個XML文檔,或者一張圖片. . . 是任何東西均可以。不管視圖自己包含什麼邏輯,都要返回響應。代碼寫在哪裏也無所謂,只要它在你的Python目錄下面。除此以外沒有更多的要求了——能夠說「沒有什麼神奇的地方」。爲了將代碼放在某處,約定是將視圖放置在項目或應用程序目錄中的名爲views.py的文件中。
下面是一個返回當前日期和時間做爲HTML文檔的視圖:
from django.shortcuts import render, HttpResponse, HttpResponseRedirect, redirect import datetime def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html)
讓咱們逐行閱讀上面的代碼:
首先,咱們從 django.shortcuts模塊導入了HttpResponse類,以及Python的datetime庫。
接着,咱們定義了current_datetime函數。它就是視圖函數。每一個視圖函數都使用HttpRequest對象做爲第一個參數,而且一般稱之爲request。
注意,視圖函數的名稱並不重要;不須要用一個統一的命名方式來命名,以便讓Django識別它。咱們將其命名爲current_datetime,是由於這個名稱可以精確地反映出它的功能。
這個視圖會返回一個HttpResponse對象,其中包含生成的響應。每一個視圖函數都負責返回一個HttpResponse對象。
django將請求報文中的請求行、首部信息、內容主體封裝成 HttpRequest 類中的屬性。 除了特殊說明的以外,其餘均爲只讀的
''' 1.HttpRequest.GET 一個相似於字典的對象,包含 HTTP GET 的全部參數。詳情請參考 QueryDict 對象。 2.HttpRequest.POST 一個相似於字典的對象,若是請求中包含表單數據,則將這些數據封裝成 QueryDict 對象。 POST 請求能夠帶有空的 POST 字典 —— 若是經過 HTTP POST 方法發送一個表單,可是表單中沒有任何的數據,QueryDict 對象依然會被建立。 所以,不該該使用 if request.POST 來檢查使用的是不是POST 方法;應該使用 if request.method == "POST" 另外:若是使用 POST 上傳文件的話,文件信息將包含在 FILES 屬性中。 注意:鍵值對的值是多個的時候,好比checkbox類型的input標籤,select標籤,須要用: request.POST.getlist("hobby") 3.HttpRequest.body 一個字符串,表明請求報文的主體。在處理非 HTTP 形式的報文時很是有用,例如:二進制圖片、XML,Json等。 可是,若是要處理表單數據的時候,推薦仍是使用 HttpRequest.POST 。 4.HttpRequest.path 一個字符串,表示請求的路徑組件(不含域名)。 例如:"/music/bands/the_beatles/" 5.HttpRequest.method 一個字符串,表示請求使用的HTTP 方法。必須使用大寫。 例如:"GET"、"POST" 6.HttpRequest.encoding 一個字符串,表示提交的數據的編碼方式(若是爲 None 則表示使用 DEFAULT_CHARSET 的設置,默認爲 'utf-8')。 這個屬性是可寫的,你能夠修改它來修改訪問表單數據使用的編碼。 接下來對屬性的任何訪問(例如從 GET 或 POST 中讀取數據)將使用新的 encoding 值。 若是你知道表單數據的編碼不是 DEFAULT_CHARSET ,則使用它。 7.HttpRequest.META 一個標準的Python 字典,包含全部的HTTP 首部。具體的頭部信息取決於客戶端和服務器,下面是一些示例: 取值: CONTENT_LENGTH —— 請求的正文的長度(是一個字符串)。 CONTENT_TYPE —— 請求的正文的MIME 類型。 HTTP_ACCEPT —— 響應可接收的Content-Type。 HTTP_ACCEPT_ENCODING —— 響應可接收的編碼。 HTTP_ACCEPT_LANGUAGE —— 響應可接收的語言。 HTTP_HOST —— 客服端發送的HTTP Host 頭部。 HTTP_REFERER —— Referring 頁面。 HTTP_USER_AGENT —— 客戶端的user-agent 字符串。 QUERY_STRING —— 單個字符串形式的查詢字符串(未解析過的形式)。 REMOTE_ADDR —— 客戶端的IP 地址。 REMOTE_HOST —— 客戶端的主機名。 REMOTE_USER —— 服務器認證後的用戶。 REQUEST_METHOD —— 一個字符串,例如"GET" 或"POST"。 SERVER_NAME —— 服務器的主機名。 SERVER_PORT —— 服務器的端口(是一個字符串)。 從上面能夠看到,除 CONTENT_LENGTH 和 CONTENT_TYPE 以外,請求中的任何 HTTP 首部轉換爲 META 的鍵時, 都會將全部字母大寫並將鏈接符替換爲下劃線最後加上 HTTP_ 前綴。 因此,一個叫作 X-Bender 的頭部將轉換成 META 中的 HTTP_X_BENDER 鍵。 8.HttpRequest.FILES 一個相似於字典的對象,包含全部的上傳文件信息。 FILES 中的每一個鍵爲<input type="file" name="" /> 中的name,值則爲對應的數據。 注意,FILES 只有在請求的方法爲POST 且提交的<form> 帶有enctype="multipart/form-data" 的狀況下才會 包含數據。不然,FILES 將爲一個空的相似於字典的對象。 9.HttpRequest.COOKIES 一個標準的Python 字典,包含全部的cookie。鍵和值都爲字符串。 10.HttpRequest.session 一個既可讀又可寫的相似於字典的對象,表示當前的會話。只有當Django 啓用會話的支持時纔可用。 完整的細節參見會話的文檔。 11.HttpRequest.user(用戶認證組件下使用) 一個 AUTH_USER_MODEL 類型的對象,表示當前登陸的用戶。 若是用戶當前沒有登陸,user 將設置爲 django.contrib.auth.models.AnonymousUser 的一個實例。你能夠經過 is_authenticated() 區分它們。 例如: if request.user.is_authenticated(): # Do something for logged-in users. else: # Do something for anonymous users. user 只有當Django 啓用 AuthenticationMiddleware 中間件時纔可用。 ------------------------------------------------------------------------------------- 匿名用戶 class models.AnonymousUser django.contrib.auth.models.AnonymousUser 類實現了django.contrib.auth.models.User 接口,但具備下面幾個不一樣點: id 永遠爲None。 username 永遠爲空字符串。 get_username() 永遠返回空字符串。 is_staff 和 is_superuser 永遠爲False。 is_active 永遠爲 False。 groups 和 user_permissions 永遠爲空。 is_anonymous() 返回True 而不是False。 is_authenticated() 返回False 而不是True。 set_password()、check_password()、save() 和delete() 引起 NotImplementedError。 New in Django 1.8: 新增 AnonymousUser.get_username() 以更好地模擬 django.contrib.auth.models.User。 */
''' 1.HttpRequest.get_full_path() 返回 path,若是能夠將加上查詢字符串。 例如:"/music/bands/the_beatles/?print=true" 注意和path的區別:http://127.0.0.1:8001/order/?name=lqz&age=10 2.HttpRequest.is_ajax() 若是請求是經過XMLHttpRequest 發起的,則返回True,方法是檢查 HTTP_X_REQUESTED_WITH 相應的首部是不是字符串'XMLHttpRequest'。 大部分現代的 JavaScript 庫都會發送這個頭部。若是你編寫本身的 XMLHttpRequest 調用(在瀏覽器端),你必須手工設置這個值來讓 is_ajax() 能夠工做。 若是一個響應須要根據請求是不是經過AJAX 發起的,而且你正在使用某種形式的緩存例如Django 的 cache middleware, 你應該使用 vary_on_headers('HTTP_X_REQUESTED_WITH') 裝飾你的視圖以讓響應可以正確地緩存。 '''
響應對象主要有三種形式:
HttpResponse()括號內直接跟一個具體的字符串做爲響應體,比較直接很簡單,因此這裏主要介紹後面兩種形式。
1
2
3
|
render(request, template_name[, context])
結合一個給定的模板和一個給定的上下文字典,並返回一個渲染後的 HttpResponse 對象。
|
參數: request: 用於生成響應的請求對象。 template_name:要使用的模板的完整名稱,可選的參數 context:添加到模板上下文的一個字典。默認是一個空字典。若是字典中的某個值是可調用的,視圖將在渲染模板以前調用它。
render方法就是將一個模板頁面中的模板語法進行渲染,最終渲染成一個html頁面做爲響應體。
傳遞要重定向的一個硬編碼的URL
def my_view(request): ... return redirect('/some/url/')
也能夠是一個完整的URL:
def my_view(request): ... return redirect('http://www.baidu.com/')
1)301和302的區別。 301和302狀態碼都表示重定向,就是說瀏覽器在拿到服務器返回的這個狀態碼後會自動跳轉到一個新的URL地址,這個地址能夠從響應的Location首部中獲取 (用戶看到的效果就是他輸入的地址A瞬間變成了另外一個地址B)——這是它們的共同點。 他們的不一樣在於。301表示舊地址A的資源已經被永久地移除了(這個資源不可訪問了),搜索引擎在抓取新內容的同時也將舊的網址交換爲重定向以後的網址; 302表示舊地址A的資源還在(仍然能夠訪問),這個重定向只是臨時地從舊地址A跳轉到地址B,搜索引擎會抓取新的內容而保存舊的網址。 SEO302好於301 2)重定向緣由: (1)網站調整(如改變網頁目錄結構); (2)網頁被移到一個新地址; (3)網頁擴展名改變(如應用須要把.php改爲.Html或.shtml)。 這種狀況下,若是不作重定向,則用戶收藏夾或搜索引擎數據庫中舊地址只能讓訪問客戶獲得一個404頁面錯誤信息,訪問流量白白喪失;再者某些註冊了多個域名的 網站,也須要經過重定向讓訪問這些域名的用戶自動跳轉到主站點等。 重定向301和302的區別
向前端返回一個json格式字符串的兩種方式
# 第一種方式 # import json # data={'name':'lqz','age':18} # data1=['lqz','egon'] # return HttpResponse(json.dumps(data1)) # 第二種方式 from django.http import JsonResponse # data = {'name': 'lqz', 'age': 18} data1 = ['lqz', 'egon'] # return JsonResponse(data) return JsonResponse(data1,safe=False)
CBV基於類的視圖(Class base view)和FBV基於函數的視圖(Function base view)
from django.views import View class AddPublish(View): def dispatch(self, request, *args, **kwargs): print(request) print(args) print(kwargs) # 能夠寫相似裝飾器的東西,在先後加代碼 obj=super().dispatch(request, *args, **kwargs) return obj def get(self,request): return render(request,'index.html') def post(self,request): request return HttpResponse('post')
print(request.FILES) print(type(request.FILES.get('file_name'))) file_name=request.FILES.get('file_name').name from django.core.files.uploadedfile import InMemoryUploadedFile with open(file_name,'wb')as f: for i in request.FILES.get('file_name').chunks(): f.write(i)
Django 模版層
你可能已經注意到咱們在例子視圖中返回文本的方式有點特別。 也就是說,HTML被直接硬編碼在 Python代碼之中。
def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html)
儘管這種技術便於解釋視圖是如何工做的,但直接將HTML硬編碼到你的視圖裏卻並非一個好主意。 讓咱們來看一下爲何:
對頁面設計進行的任何改變都必須對 Python 代碼進行相應的修改。 站點設計的修改每每比底層 Python 代碼的修改要頻繁得多,所以若是能夠在不進行 Python 代碼修改的狀況下變動設計,那將會方便得多。
Python 代碼編寫和 HTML 設計是兩項不一樣的工做,大多數專業的網站開發環境都將他們分配給不一樣的人員(甚至不一樣部門)來完成。 設計者和HTML/CSS的編碼人員不該該被要求去編輯Python的代碼來完成他們的工做。
程序員編寫 Python代碼和設計人員製做模板兩項工做同時進行的效率是最高的,遠勝於讓一我的等待另外一我的完成對某個既包含 Python又包含 HTML 的文件的編輯工做。
基於這些緣由,將頁面的設計和Python的代碼分離開會更乾淨簡潔更容易維護。 咱們可使用 Django的 模板系統 (Template System)來實現這種模式,這就是本章要具體討論的問題
python的模板:HTML代碼+模板語法
def current_time(req): # ================================原始的視圖函數 # import datetime # now=datetime.datetime.now() # html="<html><body>如今時刻:<h1>%s.</h1></body></html>" %now # ================================django模板修改的視圖函數 # from django.template import Template,Context # now=datetime.datetime.now() # t=Template('<html><body>如今時刻是:<h1>{{current_date}}</h1></body></html>') # #t=get_template('current_datetime.html') # c=Context({'current_date':str(now)}) # html=t.render(c) # # return HttpResponse(html) #另外一種寫法(推薦) import datetime now=datetime.datetime.now() return render(req, 'current_datetime.html', {'current_date':str(now)[:19]})
模版語法重點:
變量:{{ 變量名 }}
1 深度查詢 用句點符
2 過濾器
標籤:{{% % }}
在 Django 模板中遍歷複雜數據結構的關鍵是句點字符, 語法:{{變量名}}
def template_test(request): name = 'lqz' li = ['lqz', 1, '18'] dic = {'name': 'lqz', 'age': 18} ll2 = [ {'name': 'lqz', 'age': 18}, {'name': 'lqz2', 'age': 19}, {'name': 'egon', 'age': 20}, {'name': 'kevin', 'age': 23} ] ll3=[] class Person: def __init__(self, name): self.name = name def test(self): print('test函數') return 11 @classmethod def test_classmethod(cls): print('類方法') return '類方法' @staticmethod def static_method(): print('靜態方法') return '靜態方法' lqz = Person('lqz') egon = Person('egon') person_list = [lqz, egon] bo = True te = test() import datetime now=datetime.datetime.now() link1='<a href="https://www.baidu.com">點我<a>' from django.utils import safestring link=safestring.mark_safe(link1) # html特殊符號對照表(http://tool.chinaz.com/Tools/htmlchar.aspx) # 這樣傳到前臺不會變成特殊字符,由於django給處理了 dot='♠' # return render(request, 'template_index.html', {'name':name,'person_list':person_list}) return render(request, 'template_index.html', locals())
<p>{{ name }}</p> <p>{{ li }}</p> <p>{{ dic }}</p> <p>{{ lqz }}</p> <p>{{ person_list }}</p> <p>{{ bo }}</p> <p>{{ te }}</p> <hr> <h3>深度查詢句點符</h3> <p>{{ li.1 }}</p> <p>{{ dic.name }}</p> <p>{{ lqz.test }}</p> <p>{{ lqz.name }}</p> <p>{{ person_list.0 }}</p> <p>{{ person_list.1.name }}</p> <hr> <h3>過濾器</h3> {#注意:冒號後面不能加空格#} <p>{{ now | date:"Y-m-d H:i:s" }}</p> {#若是變量爲空,設置默認值,空數據,None,變量不存在,都適用#} <p>{{ name |default:'數據爲空' }}</p> {#計算長度,只有一個參數#} <p>{{ person_list |length }}</p> {#計算文件大小#} <p>{{ 1024 |filesizeformat }}</p> {#字符串切片,前閉後開,前面取到,後面取不到#} <p>{{ 'hello world lqz' |slice:"2:-1" }}</p> <p>{{ 'hello world lqz' |slice:"2:5" }}</p> {#截斷字符,至少三個起步,由於會有三個省略號(傳負數,1,2,3都是三個省略號)#} <p>{{ '劉清政 world lqz' |truncatechars:"4" }}</p> {#截斷文字,以空格作區分,這個不算省略號#} <p>{{ '劉清政 是 大帥比 謝謝' |truncatewords:"1" }}</p> <p>{{ link1 }}</p> <p>{{ link1|safe }}</p> <p>{{ link }}</p> <p>♠</p> <p>{{ dot }}</p> {#add 能夠加負數,傳數字字符串均可以#} <p>{{ "10"|add:"-2" }}</p> <p>{{ li.1|add:"-2" }}</p> <p>{{ li.1|add:2 }}</p> <p>{{ li.1|add:"2" }}</p> <p>{{ li.1|add:"-2e" }}</p> {#upper#} <p>{{ name|upper }}</p> <p>{{ 'LQZ'|lower }}</p> <hr> <h3>模版語法之標籤</h3> {#for 循環 循環列表,循環字典,循環列表對象#} <ui> {% for foo in dic %} {{ foo }} {% endfor %} {#也能夠混用html標籤#} {% for foo in li %} <ul>foo</ul> {% endfor %} </ui> {#表格#} <table border="1"> {% for foo in ll2 %} <tr> <td>{{ foo.name }}</td> <td>{{ foo.age }}</td> </tr> {% endfor %} </table> <table border="1"> {#'parentloop': {}, 'counter0': 0, 'counter': 1, 'revcounter': 4, 'revcounter0': 3, 'first': True, 'last': False}#} {% for foo in ll2 %} <tr> <td>{{ forloop.counter }}</td> <td>{{ foo.name }}</td> <td>{{ foo.age }}</td> </tr> {% endfor %} </table> {% for foo in ll5 %} <p>foo.name</p> {% empty %} <p>空的</p> {% endfor %} <hr> <h3>if判斷</h3> {% if name %} <a href="">hi {{ name }}</a> <a href="">註銷</a> {% else %} <a href="">請登陸</a> <a href="">註冊</a> {% endif %} {#還有elif#} <hr> <h3>with</h3> {% with ll2.0.name as n %} {{ n }} {% endwith %} {{ n }} {% load my_tag_filter %} {{ 3|multi_filter:3 }} {#傳參必須用空格區分#} {% multi_tag 3 9 10 %} {#能夠跟if連用#} {% if 3|multi_filter:3 > 9 %} <p>大於</p> {% else %} <p>小於</p> {% endif %}
注意:句點符也能夠用來引用對象的方法(無參數方法):
<h4>字典:{{ dic.name.upper }}<
/
h4>
語法: {{obj|filter__name:param}} 變量名字|過濾器名稱:變量
default
若是一個變量是false或者爲空,使用給定的默認值。不然,使用變量的值。例如:
{{ value|default:"nothing" }}
返回值的長度。它對字符串和列表都起做用。例如: {{ value|length }} 若是 value 是 ['a', 'b', 'c', 'd'],那麼輸出是 4。
filesizeformat
將值格式化爲一個 「人類可讀的」 文件尺寸 (例如 '13 KB'
, '4.1 MB'
, '102 bytes'
, 等等)。例如: {{ value|filesizeformat }} 若是 value
是 123456789,輸出將會是 117.7 MB
。
若是 value=datetime.datetime.now()
{{ value|date:"Y-m-d" }}
若是 value="hello world" {{ value|slice:"2:-1" }}
若是字符串字符多於指定的字符數量,那麼會被截斷。截斷的字符串將以可翻譯的省略號序列(「...」)結尾。
參數:要截斷的字符數
例如: {{ value|truncatechars:9 }}
Django的模板中會對HTML標籤和JS等語法標籤進行自動轉義,緣由顯而易見,這樣是爲了安全。可是有的時候咱們可能不但願這些HTML元素被轉義,好比咱們作一個內容管理系統,後臺添加的文章中是通過修飾的,這些修飾多是經過一個相似於FCKeditor編輯加註了HTML修飾符的文本,若是自動轉義的話顯示的就是保護HTML標籤的源文件。爲了在Django中關閉HTML的自動轉義有兩種方式,若是是一個單獨的變量咱們能夠經過過濾器「|safe」的方式告訴Django這段代碼是安全的沒必要轉義。好比: value="<a href="">點擊</a>" {{ value|safe}}
標籤看起來像是這樣的: {% tag %}
。標籤比變量更加複雜:一些在輸出中建立文本,一些經過循環或邏輯來控制流程,一些加載其後的變量將使用到的額外信息到模版中。一些標籤須要開始和結束標籤 (例如{% tag %} ...
標籤 內容 ... {% endtag %})。
遍歷每個元素:
{% for person in person_list %} <p>{{ person.name }}</p> {% endfor %}
能夠利用{% for obj in list reversed %}反向完成循環。
遍歷一個字典:
{% for key,val in dic.items %} <p>{{ key }}:{{ val }}</p> {% endfor %}
注:循環序號能夠經過{{forloop}}顯示
forloop.counter The current iteration of the loop (1-indexed) 當前循環的索引值(從1開始)
forloop.counter0 The current iteration of the loop (0-indexed) 當前循環的索引值(從0開始)
forloop.revcounter The number of iterations from the end of the loop (1-indexed) 當前循環的倒序索引值(從1開始)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed) 當前循環的倒序索引值(從0開始)
forloop.first True if this is the first time through the loop 當前循環是否是第一次循環(布爾值)
forloop.last True if this is the last time through the loop 當前循環是否是最後一次循環(布爾值)
forloop.parentloop 本層循環的外層循環
for 標籤帶有一個可選的{% empty %} 從句,以便在給出的組是空的或者沒有被找到時,能夠有所操做。
{% for person in person_list %} <p>{{ person.name }}</p> {% empty %} <p>sorry,no person here</p> {% endfor %}
{% if %}會對一個變量求值,若是它的值是「True」(存在、不爲空、且不是boolean類型的false值),對應的內容塊會輸出。
{% if num > 100 or num < 0 %} <p>無效</p> {% elif num > 80 and num < 100 %} <p>優秀</p> {% else %} <p>湊活吧</p> {% endif %}
if語句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判斷。
使用一個簡單地名字緩存一個複雜的變量,當你須要使用一個「昂貴的」方法(好比訪問數據庫)不少次的時候是很是有用的
例如:
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
不要寫成as
{% csrf_token%}
這個標籤用於跨站請求僞造保護
一、在settings中的INSTALLED_APPS配置當前app,否則django沒法找到自定義的simple_tag.
二、在app中建立templatetags模塊(模塊名只能是templatetags)
三、建立任意 .py 文件,如:my_tags.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
from django import template
from django.utils.safestring import mark_safe
register = template.Library() #register的名字是固定的,不可改變
@register . filter
def filter_multi(v1,v2):
return v1 * v2
<br>
@register .simple_tag
def simple_tag_multi(v1,v2):
return v1 * v2
<br>
@register .simple_tag
def my_input( id ,arg):
result = "<input type='text' id='%s' class='%s' />" % ( id ,arg,)
return mark_safe(result)
|
四、在使用自定義simple_tag和filter的html文件中導入以前建立的 my_tags.py
1
|
{ % load my_tags % }
|
五、使用simple_tag和filter(如何調用)
1
2
3
4
5
6
7
8
9
10
|
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .html
{ % load xxx % }
# num=12
{{ num|filter_multi: 2 }} #24
{{ num|filter_multi: "[22,333,4444]" }}
{ % simple_tag_multi 2 5 % } 參數不限,但不能放在 if for 語句中
{ % simple_tag_multi num 5 % }
|
注意:filter能夠用在if等語句後,simple_tag不能夠
{% if num|filter_multi:30 > 100 %} {{ num|filter_multi:30 }} {% endif %}
語法:{% include '模版名稱' %}
如:{% include 'adv.html' %}
<div class="adv"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> Panel content </div> </div> <div class="panel panel-danger"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> Panel content </div> </div> <div class="panel panel-warning"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> Panel content </div> </div> </div> adv.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"> {# <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">#} <style> * { margin: 0; padding: 0; } .header { height: 50px; width: 100%; background-color: #369; } </style> </head> <body> <div class="header"></div> <div class="container"> <div class="row"> <div class="col-md-3"> {% include 'adv.html' %} </div> <div class="col-md-9"> {% block conn %} <h1>你好</h1> {% endblock %} </div> </div> </div> </body> </html> base.html
{% extends 'base.html' %}
{% block conn %}
{{ block.super }}
是啊
{% endblock conn%}
order.html
Django模版引擎中最強大也是最複雜的部分就是模版繼承了。模版繼承可讓您建立一個基本的「骨架」模版,它包含您站點中的所有元素,而且能夠定義可以被子模版覆蓋的 blocks 。
經過從下面這個例子開始,能夠容易的理解模版繼承:
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css"/> <title>{% block title %}My amazing site{% endblock %}</title> </head> <body> <div id="sidebar"> {% block sidebar %} <ul> <li><a href="/">Home</a></li> <li><a href="/blog/">Blog</a></li> </ul> {% endblock %} </div> <div id="content"> {% block content %}{% endblock %} </div> </body> </html>
這個模版,咱們把它叫做 base.html
, 它定義了一個能夠用於兩列排版頁面的簡單HTML骨架。「子模版」的工做是用它們的內容填充空的blocks。
在這個例子中, block
標籤訂義了三個能夠被子模版內容填充的block。 block
告訴模版引擎: 子模版可能會覆蓋掉模版中的這些位置。
子模版可能看起來是這樣的:
{% extends "base.html" %} {% block title %}My amazing blog{% endblock %} {% block content %} {% for entry in blog_entries %} <h2>{{ entry.title }}</h2> <p>{{ entry.body }}</p> {% endfor %} {% endblock %}
extends
標籤是這裏的關鍵。它告訴模版引擎,這個模版「繼承」了另外一個模版。當模版系統處理這個模版時,首先,它將定位父模版——在此例中,就是「base.html」。
那時,模版引擎將注意到 base.html
中的三個 block
標籤,並用子模版中的內容來替換這些block。根據 blog_entries
的值,輸出可能看起來是這樣的:
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css" /> <title>My amazing blog</title> </head> <body> <div id="sidebar"> <ul> <li><a href="/">Home</a></li> <li><a href="/blog/">Blog</a></li> </ul> </div> <div id="content"> <h2>Entry one</h2> <p>This is my first entry.</p> <h2>Entry two</h2> <p>This is my second entry.</p> </div> </body> </html>
請注意,子模版並無定義 sidebar
block,因此係統使用了父模版中的值。父模版的 {% block %}
標籤中的內容老是被用做備選內容(fallback)。
這種方式使代碼獲得最大程度的複用,而且使得添加內容到共享的內容區域更加簡單,例如,部分範圍內的導航。
這裏是使用繼承的一些提示:
若是你在模版中使用 {% extends %}
標籤,它必須是模版中的第一個標籤。其餘的任何狀況下,模版繼承都將沒法工做。
在base模版中設置越多的 {% block %}
標籤越好。請記住,子模版沒必要定義所有父模版中的blocks,因此,你能夠在大多數blocks中填充合理的默認內容,而後,只定義你須要的那一個。多一點鉤子總比少一點好。
若是你發現你本身在大量的模版中複製內容,那可能意味着你應該把內容移動到父模版中的一個 {% block %}
中。
If you need to get the content of the block from the parent template, the {{ block.super }}
variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it. Data inserted using {{ block.super }}
will not be automatically escaped (see the next section), since it was already escaped, if necessary, in the parent template.
爲了更好的可讀性,你也能夠給你的 {% endblock %}
標籤一個 名字 。例如:
1
2
3
|
{ % block content % }
...
{ % endblock content % }
|
在大型模版中,這個方法幫你清楚的看到哪個 {% block %}
標籤被關閉了。
block
標籤。