django-xadmin定制之分页显示数量
环境:xadmin-for-python3 python3.5.2 django1.9.12
主要思路:利用django-xadmin的插件原理和原有分页插件的逻辑,单独定义一个分页显示数插件,效果如下“每页”:
以下为相关代码:
1. 新建一个plugins/listperpage.py
from django.utils.safestring import mark_safe import xadmin from xadmin.views import BaseAdminPlugin from django.template import loader from django.utils.html import escape class ListPerPagePlugin(BaseAdminPlugin): show_list_per_page = True list_per_page_choices = [20, 50, 100, 500] def init_request(self, *args, **kwargs): try: self.admin_view.list_per_page = int(self.request.GET.get('list_per_page', self.admin_view.list_per_page)) except ValueError as e: print(repr(e)) if self.admin_view.list_per_page>10000: self.admin_view.list_per_page = 10000 # 最大10000 return bool(self.show_list_per_page) def get_context(self, context): list_per_page_range = [] for per_page in self.list_per_page_choices: list_per_page_range.append(mark_safe('<a href="%s"%s><p class="text-left">%d</p></a> ' % (escape(self.get_query_string({'list_per_page': per_page})), (per_page == self.admin_view.list_per_page and ' class="btn btn-sm disabled"' or ' class="btn btn-sm"'), per_page))) context.update({'list_per_page_range': list_per_page_range, 'list_per_page_required': (not self.admin_view.show_all or not self.admin_view.can_show_all) and self.admin_view.multi_page}) return context # 对应model_list.html中的view_block 'bx_list_per_page' def block_bx_list_per_page(self, context, nodes): nodes.append(loader.render_to_string('base/blocks/bx_list_per_page.html', context_instance=context))
新建bx_list_per_page.html文件:
{% if list_per_page_required %} <div class="dropdown" style="display:inline-block;"> <button class="btn btn-default btn-sm dropdown-toggle" style="line-height:1.42" type="button" data-toggle="dropdown">每页 <span class="caret"></span></button> <ul class="dropdown-menu"> {% for num in list_per_page_range %} <li>{{ num }}</li> {% endfor %} </ul> </div> {% endif %}
2. 在合适的adminx.py中注册这个plugin, 注意这个adminx.py文件所在的app package必须是有配置在INSTALLED_APPS中:
from xadmin.views import ListAdminView from .plugins.listperpage import ListPerPagePlugin xadmin.site.register_plugin(ListPerPagePlugin, ListAdminView)
3. 更改djano-xadmin中的model_list.html文件,分页部分增加了
view_block 'bx_list_per_page' :
<ul class="pagination pagination-sm pagination-left pagination-inline"> {% view_block 'pagination' 'small' %}<li>{% view_block 'bx_list_per_page' %}</li> </ul>