4
什麼是最簡單的方式來生成模型的列表視圖,可點擊標題和搜索(過濾器)字段,或多或少像管理網站?我讀了一些關於通用視圖的內容,但是我沒有看到一個簡單的解決方案。django:自動生成與搜索列表視圖(管理風格)
什麼是最簡單的方式來生成模型的列表視圖,可點擊標題和搜索(過濾器)字段,或多或少像管理網站?我讀了一些關於通用視圖的內容,但是我沒有看到一個簡單的解決方案。django:自動生成與搜索列表視圖(管理風格)
通用視圖非常適合創建這種功能。表格排序,搜索和分頁然後可以在客戶端使用JavaScript插件進行,如jQuery和DataTables。
爲了實現這個目標,你需要定義一個通用的觀點,包括它在urls.py:其他
from django.views.generic import ListView
from exampleapp.models import BlogPost
class BlogPostListView(ListView):
""""Class that extends generic ListView"""
template_name = "list.html"
def get_queryset(self):
return BlogPost.objects.filter(published=True)
urlpatterns = patterns('',
url('^list/$', BlogPostListView.as_view()),
)
一切都在模板文件中完成的。下面的代碼顯示一個包含3列的表格並初始化DataTables插件。分頁按鈕和搜索輸入將被添加,並且標題單元格可以點擊以便按給定列進行排序。
<script type="text/javascript" language="javascript" src="http://datatables.net/release-datatables/media/js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="http://datatables.net/release-datatables/media/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function(){
// Initalize DataTables on <table> tag with id="example"
$('#example').dataTable();
});
</script>
<table id="example">
<thead> <!-- header row -->
<tr>
<td>ID</td>
<td>column1</td>
<td>column2</td>
</tr>
</thead>
<tbody> <!-- data -->
{% for item in object_list.all %}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.column1 }}</td>
<td>{{ item.column2 }}</td>
</tr>
{% endfor %}
</tbody>
</table>