《雲頂之弈》11.10版小惡魔陣容運營教學
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">