Django 應用,寫一個真正有用的視圖

每個視圖必須要做的只有兩件事:返回一個包含被請求頁面內(nèi)容的 HttpResponse 對象,或者拋出一個異常,比如 Http404 。

當然你也可以從數(shù)據(jù)庫里讀取記錄,可以使用一個模板引擎(比如 Django 自帶的,或者其他第三方的),可以生成一個 PDF 文件,或者輸出一個 XML

寫一個真正有用的視圖

我們在 index() 函數(shù)里插入了一些新內(nèi)容,在上一節(jié)中講過如果創(chuàng)建視圖,讓它能展示數(shù)據(jù)

from django.http import HttpResponse

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    output = ', '.join([q.question_text for q in latest_question_list])
    return HttpResponse(output)

這里有個問題:頁面的設計寫死在視圖函數(shù)的代碼里的。如果你想改變頁面的樣子,你需要編輯 Python 代碼。所以讓我們使用 Django 的模板系統(tǒng)

首先,在你的 polls 目錄里創(chuàng)建一個 templates 目錄。Django 將會在這個目錄里查找模板文件。

你項目中setting.py的 TEMPLATES 配置項描述了 Django 如何載入和渲染模板。默認的設置文件設置了 DjangoTemplates 后端,并將 APP_DIRS 設置成了 True。這一選項將會讓 DjangoTemplates 在每個 INSTALLED_APPS 文件夾中尋找 "templates" 子目錄。所以你只需要使用 polls/index.html 就可以引用到這一模板了。

將下面的代碼輸入到剛剛創(chuàng)建的polls/index.html 模板文件中:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Django官方網(wǎng)站 </title>
    {% load staticfiles %}
</head>
<body>
    <p> {{ hello }}</p>
    <img src="{% static "img/2019-04-25.png" %}" alt="My image">
</body>
</html>

然后,讓我們更新一下 polls/views.py 里的 index 視圖來使用模板:

from django.http import HttpResponse
from django.template import loader

from .models import Question


def index(request):
    context = 'hello word'
    template = loader.get_template('polls/index.html')
    return HttpResponse(template.render(context, request))

上述代碼的作用是,載入 polls/index.html 模板文件,并且向它傳遞一個上下文(context)。這個上下文是一個字典,它將模板內(nèi)的變量映射為 Python 對象。

一個快捷函數(shù): render()

「載入模板,填充上下文,再返回由它生成的 HttpResponse 對象」是一個非常常用的操作流程。于是 Django 提供了一個快捷函數(shù),我們用它來重寫 index() 視圖:

from django.shortcuts import render

from .models import Question


def index(request):
    context = 'hello word'
    return render(request, 'polls/index.html', context)

我們不再需要導入 loaderHttpResponse 。不過如果你還有其他函數(shù)(比如說 detail, results, 和 vote )需要用到它的話,就需要保持 HttpResponse 的導入。

總結:

Django內(nèi)views常用到到有三個方法,分別是:
1.HttpResponse() :它是作用是內(nèi)部傳入一個字符串或變量,然后發(fā)給瀏覽器。
2.render():它的作用就是將數(shù)據(jù)填充進模板文件,最后把結果返回給瀏覽器。可接收三個參數(shù),一是request參數(shù),二是待渲染的html模板文件,三是保存具體數(shù)據(jù)的字典參數(shù)。
3.redirect()接受一個URL參數(shù),表示讓瀏覽器跳轉(zhuǎn)去指定的URL.

舉例:

def index(request):
    # 業(yè)務邏輯代碼
    return HttpResponse("OK")

def index(request):
    # 業(yè)務邏輯代碼
    return render(request, "index.html", {"name": "monicx", "hobby": ["reading", "blog"]})

def index(request):
    # 業(yè)務邏輯代碼
    return redirect("https://blog.csdn.net/miaoqinian")

## 拋出 404 錯誤?

如果指定問題 ID 所對應的問題不存在,這個視圖就會拋出一個 Http404 異常。

我們暫時在 polls/detail.html 里把下面這段輸進去:

{{ question }}

一個快捷函數(shù): get_object_or_404()?

嘗試用 get() 函數(shù)獲取一個對象,如果不存在就拋出 Http404 錯誤也是一個普遍的流程。Django 也提供了一個快捷函數(shù),下面是修改后的詳情 detail() 視圖代碼:

from django.shortcuts import get_object_or_404, render

from .models import Question
# ...
def detail(request, question_id):
   question = get_object_or_404(Question, pk=question_id)
   return render(request, 'polls/detail.html', {'question': question})

也有 get_list_or_404() 函數(shù),工作原理和 get_object_or_404() 一樣,除了 get() 函數(shù)被換成了 filter() 函數(shù)。如果列表為空的話會拋出 Http404 異常。

更多內(nèi)容參考:編寫你的第一個 Django 應用,第 3 部分

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容