四.Django的template

如果要求不高,可以使用django admin做CRUD的操作,當然django admin也有許多定製方法,具體可以參見https://docs.djangoproject.com/en/1.9/ref/contrib/admin/。但是對於大多數的應用來說,還是希望自己能夠可控地實現增刪改查功能,並將其在頁面上實現。那麼,我們就需要通過template來存放我們的頁面。

 

以下是Django官網對template的介紹

A template contains the static parts of thedesired HTML output as well as some special syntax describing how dynamiccontent will be inserted.Django defines a standard API for loading andrendering templates regardless of the backend. Loading consists of finding thetemplate for a given identifier and preprocessing it, usually compiling it toan in-memory representation. Rendering means interpolating the template withcontext data and returning the resulting string.

 

簡言之,在template中,我們存放HTML頁面,並通過Django的API能夠調用這些界面,同時能夠把一些數據傳遞到這些頁面上。當然,Django也提供了一個非常強大的模板語言,DTL。

 

在這一小節中,我們通過頁面來顯示一下之前通過admin site存放入的信息。

 

1.      在echo文件夾下建立templates目錄

2.      在urls中指定跳轉路徑

urls.py:

from django.conf.urls import url
from django.contrib import admin
import echo.views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    #設定相應跳轉路徑
    url(r'^lists/', echo.views.lists),
]


3.     在views中定義相應函數響應:

views.py:

# -*- coding: UTF-8 -*-
from django.shortcuts import render
from .models import Node
# Create your views here.

def lists(request):
    #從node節點中獲取所有數據
    data = Node.objects.all()
    #建立context字典,將值傳遞到相應頁面
    context = {
        'data': data,
    }
    #跳轉到相應頁面,並將值傳遞過去
    return render(request,'lists.html',context)<strong>
</strong>


在這個函數中,有一行data = Node.objects.all(),這是通過DJANGO的ORM來進行SQL操作,具體的ORM表達式可以參見django的相關文檔,在此不再贅述。

 

4.   在templates目錄下建立lists.html文件,並將views傳遞來的data數據顯示在頁面上,傳遞過來的data是一個對象,可以通過for循環來將其中的值顯示。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <table>
        <tr>
            <th>節點名稱</th>
            <th>節點地址</th>
            <th>節點類型</th>
        </tr>
        {% for item in data %}
            <tr>
                <td>{{ item.node_name }}</td>
                <td>{{ item.node_address }}</td>
                <td>{{ item.node_type }}</td>
            </tr>
        {% endfor %}
    </table>
</body>
</html>


其中用{% %}括起的就是django的模板語言,在django的模板語言中,包含了類似於for循環,if等條件判斷語句,可以非常靈活地滿足用戶的各種需求。其中,{{ data }}用來在頁面上顯示data的值。此後,我們還將提到的include和block功能,將會非常方便地繼承網頁。

 

1.    訪問url中定義的lists的路徑,就可以訪問相應頁面了

http://127.0.0.1:8000/lists/








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章