1. 程式人生 > 實用技巧 >Django筆記&教程 2-4 檢視常用

Django筆記&教程 2-4 檢視常用

Django 自學筆記兼學習教程第2章第4節——檢視常用
點選檢視教程總目錄

1 - shortcut

檢視函式需要返回一個HttpResponse物件或者其子類物件。
不過很多時候直接手寫建立一個HttpResponse物件比較麻煩。

所以Django實現了建立HttpResponse物件的一些快捷方法:
這些方法收集在django.shortcuts包中。

比如下一章將會頻繁使用的render方法,
還有本章第二部分會介紹的redirect方法,
都是django.shortcuts包中的。

django.shortcuts 官方文件:shortcuts
django.shortcuts

官方介紹如下:
The package django.shortcuts collects helper functions and classes that “span” multiple levels of MVC.
In other words, these functions/classes introduce controlled coupling for convenience’s sake.

2 - reverse 反向解析

知道urlpattern名,可通過reverse函式反向解析出對應的url。
該方法常在模型的get_absolute_url()get_success_url()

中用到,然後用於重定向,一般直接使用本文第三部分的重定向語法覆蓋實現這些。

reverse方法位於django.urls中,但也可以從django.shortcuts包中匯入。
其使用語法為:
reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)

使用示例:
比如有url:

path('login/', views.home, name="login"),
path('user/login/<slug:kind>', views.login, name="login"),

那麼在django互動式命令列下,效果如下

>>> reverse("login")
'/user/login/'
>>> reverse("login", kwargs={'kind': 'student'})
'/user/login/student'

3 - 重定向

重定向場景:使用者未登入情況下,訪問需要登入才能訪問的url,往往需要重定向到登入頁。

重定向程式碼一般寫在檢視函式中:檢視函式返回一個重定向物件django.http.HttpResponseRedirect

不過我們一般使用shortcut裡的redirect方法來獲得一個重定向物件。

語法如下:
redirect(to, *args, permanent=False, **kwargs)
根據傳遞的引數返回一個對應的HttpResponseRedirect。
傳入的引數可以是:

  • 一個模型(model): 模型的get_absolute_url()方法將被呼叫。
  • 一個檢視名,可能帶有引數: 將呼叫reverse()函式來反向解析名稱。
  • 絕對或相對URL: 將按原樣用於重定向位置。

舉例:
比如有url:

path('user/login/<slug:kind>', views.login, name="login"),

那麼在django互動式命令列下,效果如下

>>> from django.shortcuts import redirect
>>> redirect("login", kind='student')
<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/user/login/student">
>>> redirect("/user/login/student")
<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/user/login/student">