#Django ListView
Explore tagged Tumblr posts
robomad · 1 year ago
Text
Implementing Pagination in Django
Introduction Pagination is a crucial feature for web applications that handle large amounts of data. It allows you to split data into manageable chunks, improving performance and user experience. Django provides built-in support for pagination, making it easy to implement in your views and templates. In this guide, we will walk you through the steps to add pagination to a Django project,…
Tumblr media
View On WordPress
0 notes
qjarchen · 8 years ago
Text
django 概念筆記(5)
Django 提供了一個簡化 view 撰寫的工具:generic views。為了達到重用並保持擴充性,generic views 是用 class 配合 factory function 實作,所以我們不再需要宣告 view functions,而是要繼承 Django 提供的 generic view classes。但這些類別裡面做的事情,其實還是和 view functions 相同。 常用的 generic views 有:DetailView:顯示一個 model instance 的內容。
ListView:顯示「數個」model instances(用 queryset 表示)的內容。支援 pagination。
CreateView:顯示一個 model form,接收 GET 與 POST 以建立 model instance。
UpdateView:和 CreateView 類似,但是是用來更新 model instance(會指定 model form 的 instance 參數)。
DeleteView:接收 POST 以刪除 model instance。也可以接收 GET,會顯示一個刪除用的 form(類似 admin 刪除時會出現的確認頁面)。
TemplateView:顯示某個特定的 template 內容。
RedirectView:回傳 redirect response。
Django 的 generic view classes——又稱 class-based views,簡稱 CBV        CBV 能做到的事情跟 function based view 完全相同,然而由於使用 class,所以當你的 view function 中有很多重複的 code 時(例如一堆 views 都需要要取得相同的 context data 時),這時 CBV 的優勢就在於可以繼承 。上章有提到 Django 內建了一些常用的 CBV,然而你會發現根本搞不懂他到底是怎麼運作的、也因此不知該如何用。因為 CBV 做了很多 magic,理解要如何使用 CBV 的最好方法可能就是直接看 CBV 的原始碼。 CBV 做的事情跟寫 view function 能做的事情其實一模一樣。
所有的 generic views 都必須繼承 View class,所以我們從它開始看起。
View class 下面有個 DetailView, DetailView 做的事情就是:檢查 HTTP 動詞是否被允許(類似 require_http_methods 的作用)。根據 URL 中的參數,在指定的 model 中取得一個 instance。用傳入的參數與前面的 instance 變成 dict,準備當作 context。取得指定的 template。將 context 與 template 組合產生 HTTP response(預設產生 HttpResponse 實例,所以是 200 OK)。這個 response 會一直往上被回傳,直到最外面的 view function。 所以其實和 view function 做的事情差不多!
Django 在把 form 轉成 HTML form 時,會自動根據欄位形態選擇合適的 HTML tag;但如果你不滿意預設值,也可以用 widgets 來明確要求 Django 在某個欄位使用特定 widget。
用 function-based views 時,我們會用 require_http_methods decorator。在 class-based views 中,我們使用 http_method_names attribute。
0 notes