2010-05-17 65 views

回答

3

通用視圖非常適合創建這種功能。表格排序,搜索和分頁然後可以在客戶端使用JavaScript插件進行,如jQueryDataTables

爲了實現這個目標,你需要定義一個通用的觀點,包括它在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>