2010-05-17 68 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>