教育行業(yè)A股IPO第一股(股票代碼 003032)

全國咨詢/投訴熱線:400-618-4000

Django快捷函數(shù)——render(),生成響應(yīng)的快捷方式

更新時間:2023年01月12日11時22分 來源:傳智教育 瀏覽次數(shù):

好口碑IT培訓(xùn)

  “載入模板→填充上下文→生成響應(yīng)消息→返回響應(yīng)對象”這一生成響應(yīng)消息、返回響應(yīng)對象的流程在視圖中非常常見,于是Django提供了快捷函數(shù)——render()來簡化這一流程。

  render()函數(shù)定義在django.shortcuts模塊中,該函數(shù)的聲明如下:

render(request, template_name, context = None, content_type = None,
status = None, using = None)

  render()函數(shù)結(jié)合給定的模板和上下文字典,返回一個渲染后的HttpResponse對象。render()函數(shù)中各參數(shù)的含義如下:

 ?、賠equest:請求對象。

 ?、趖emplate_name:模板名稱或模板序列的名稱。若該參數(shù)接收模板序列,則使用序列中的第一個模板。

  ③context:接收一個用于填充模板上下文的dict類型的數(shù)據(jù),默認(rèn)為None。若不為None,則在呈現(xiàn)模板之前將其整合到模板中。

 ?、躢ontent_type:用于指定響應(yīng)信息的MIME類型,如“text/html;charset=UTF-8”。

 ?、輘tatus:指定響應(yīng)的狀態(tài)碼,默認(rèn)為200。

  ⑥using:指定加載模板時所用的模板引擎名稱。

  使用render()函數(shù)重寫5.1節(jié)中的視圖函數(shù),具體代碼如下:

from django.shortcuts import render
def curr_time(request):
    now = datetime.datetime.now()
    context = {                         # 上下文字典
        'now': now,
    }
    return render(request, "time.html",context)

  除render()以外,shortcuts模塊中還定義了快捷方式redirect()、get_object_or_404()、get_list_or_404()。

0 分享到:
和我們在線交談!