Django - 建立檢視



檢視函式,簡稱“檢視”,只是一個 Python 函式,它接收一個 Web 請求並返回一個 Web 響應。此響應可以是網頁的 HTML 內容、重定向、404 錯誤、XML 文件、影像等。例如:您使用檢視來建立網頁,請注意,您需要將檢視與 URL 關聯才能將其顯示為網頁。

在 Django 中,檢視必須在應用的 views.py 檔案中建立。

簡單檢視

我們將在 myapp 中建立一個簡單的檢視,顯示“歡迎使用我的應用!”。

檢視以下檢視:

from django.http import HttpResponse

def hello(request):
   text = """<h1>welcome to my app !</h1>"""
   return HttpResponse(text)

在此檢視中,我們使用 HttpResponse 渲染 HTML(您可能已經注意到,我們在檢視中硬編碼了 HTML)。要將此檢視顯示為頁面,我們只需要將其對映到 URL(這將在後續章節中討論)。

之前我們使用 HttpResponse 在檢視中渲染 HTML。這不是渲染頁面的最佳方法。Django 支援 MVT 模式,因此要使前面的檢視類似於 Django - MVT,我們需要:

一個模板:myapp/templates/hello.html

現在我們的檢視將如下所示:

from django.shortcuts import render

def hello(request):
   return render(request, "myapp/template/hello.html", {})

檢視還可以接受引數:

from django.http import HttpResponse

def hello(request, number):
   text = "<h1>welcome to my app number %s!</h1>"% number
   return HttpResponse(text)

當連結到 URL 時,頁面將顯示作為引數傳遞的數字。請注意,引數將透過 URL 傳遞(在下一章中討論)。

廣告

© . All rights reserved.