本帖最后由 丁柳 于 2019-4-11 14:26 编辑
1、在/site-packages/xadmin/plugins中新增excel.py文件
文件内容:
[Python] 纯文本查看 复制代码 import xadmin
from xadmin.views import BaseAdminPlugin, ListAdminView
from django.template import loader
from xadmin.plugins.utils import get_context_dict
class ListImportExcelPlugin(BaseAdminPlugin):
import_excel = False
def init_request(self, *args, **kwargs):
return bool(self.import_excel)
def block_top_toolbar(self, context, nodes):
nodes.append(
loader.render_to_string('xadmin/excel/model_list.top_toolbar.import.html', get_context_dict(context)))
xadmin.site.register_plugin(ListImportExcelPlugin, ListAdminView)
注意:Django2.0以后rander_to_string的第二个参数必须为dict格式,导入了get_context_dict方法,将context转换
2、将execl.py插件注册到xadmin的plugins中,修改site-packages/xadmin/plugins的__init__.py,
3、创建导入模板
xadmin/excel/model_list.top_toolbar.import.html
文件内容:
[HTML] 纯文本查看 复制代码 {% load i18n %}
<div class="btn-group export">
<a class="dropdown-toggle btn btn-default btn-sm" data-toggle="dropdown" href="#">
<i class="icon-share"></i> 导入 <span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
<li><a data-toggle="modal" data-target="#export-modal-import-excel"><i class="icon-circle-arrow-down"></i> 导入 Excel</a></li>
</ul>
<script>
function fileChange(target){
var imgName = document.all.submit_upload.value;
var ext,idx;
if (imgName == ''){
document.all.submit_upload_b.disabled=true;
alert("请选择需要上传的 xls 文件!");
return;
} else {
idx = imgName.lastIndexOf(".");
if (idx != -1){
ext = imgName.substr(idx+1).toUpperCase();
ext = ext.toLowerCase( );
if (ext != 'xls' && ext != 'xlsx'){
document.all.submit_upload_b.disabled=true;
alert("只能上传 .xls 类型的文件!");
return;
}
} else {
document.all.submit_upload_b.disabled=true;
alert("只能上传 .xls 类型的文件!");
return;
}
}
}
</script>
<div id="export-modal-import-excel" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">导入 Excel</h4>
</div>
<div class="modal-body">
<input type="file" name="excel" id="submit_upload">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">{% trans "Close" %}</button>
<button class="btn btn-success" type="submit" id="submit_upload_b"><i class="icon-share"></i> 导入</button>
</div>
</form>
</div>
</div>
</div>
</div>
4.在Django项目的配置文件INSTALLED_APP中添加xadmin和crispy_froms
5.在应用中新建adminx.py文件,后台管理模型如需导入excel文件的,设置import_excel=True,则在该模型类的后台管理页面出现导入按钮
|