gpt4 book ai didi

django:自动生成带有搜索功能的 ListView (管理员风格)

转载 作者:行者123 更新时间:2023-12-04 20:24:22 26 4
gpt4 key购买 nike

为模型生成 ListView 的最简单方法是什么,具有可点击的标题和搜索(过滤器)字段,或多或少类似于管理站点?我阅读了一些关于通用 View 的内容,但没有看到简单的解决方案。

最佳答案

通用 View 非常适合创建这种功能。然后可以使用诸如 jQuery 之类的 javascript 插件在客户端执行表格排序、搜索和分页。和 DataTables .

为此,您需要定义一个通用 View 并将其包含在 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>

关于django:自动生成带有搜索功能的 ListView (管理员风格),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2849406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com