我們將在 myapp 創(chuàng)建一個(gè)簡(jiǎn)單的視圖顯示: "welcome to nhooo !"
查看如下的視圖 ?
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.soo66.com # Date : 2020-08-08 from django.http import HttpResponse def hello(request): text = """<h1>welcome to nhooo !</h1>""" return HttpResponse(text)
在這個(gè)視圖中,我們使用 HttpResponse 呈現(xiàn) HTML(你可能已經(jīng)注意到了,我們將HTML硬編碼在視圖中)。 在這個(gè)視圖我們只是需要把它映射到一個(gè)URL(這將在即將到來的章節(jié)中討論)的頁面。
我們使用 HttpResponse 在渲染視圖 HTML 之前。 這不是渲染網(wǎng)頁的最佳方式。Django支持MVT模式,從而先渲染視圖,Django - MVT這是我們需要的?
一個(gè)模板文件: myapp/templates/hello.html
現(xiàn)在,我們的視圖內(nèi)容如下 ?
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.soo66.com # Date : 2020-08-08 from django.shortcuts import render def hello(request): return render(request, "myapp/template/hello.html", {})
視圖還可以接受的參數(shù) -
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.soo66.com # Date : 2020-08-08 from django.http import HttpResponse def hello(request, number): text = "<h1>welcome to my app number %s!</h1>"% number return HttpResponse(text)
當(dāng)鏈接到一個(gè)網(wǎng)址,頁面會(huì)顯示作為參數(shù)傳遞的數(shù)值。 注意,參數(shù)將通過URL(在下一章節(jié)中討論)傳遞。