1、要安装django-import-export版本,并将此应用注册到
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.devices.apps.DevicesConfig',
'xadmin',
'crispy_forms',
'envs',
'assets',
'meeting',
'terminals',
'import_export',
]
2、使用的tablib to 0.12.1版本,否则会出现导入csv时报错‘Error encountered while trying to read file: test.csv’
Problem
Error encountered while trying to read file CSV with python 2.7 #957
Solution
Downgrade tablib to 0.12.1
Acceptance Criteria
Doc updated with good dependencies
3、导入时报错: "This is forbidden when an 'atomic' block is active."
TransactionManagementError: This is forbidden when an 'atomic' block is active.
原因分析:详见https://github.com/django-import-export/django-import-export/issues/609
This is because import_export.resource.Resource.import_data()
tests for connection.features.supports_transaction
. This is OK on most RDBMS, but on MySQL the support for transactions depends on the database engine being used, so Django runs a test to see if the DB supports transactions. During the test, a temporary table is created and also calls set_autocommit(False)
. That call can only be executed outside of an atomic
block (Django code test for in_atomic_block
for the DB connection).
This also has the side effect the table created by Django (called ROLLBACK_TEST) to test transaction support is never deleted from the DB, because the rollback to the savepoint marked by Django is never performed.
I'll submit a Pull Request with a short patch to prevent this: if the import_data()
is running inside an atomic block, then we know the DB supports transactions and we don't test for connection.features.supports_transaction
.
解决办法:
supports_transactions = getattr(connection.features, "supports_transactions", False)
改为:
supports_transactions = getattr(connection, 'in_atomic_block', False) or getattr(connection.features, "supports_transactions", False)
4、为了控制在导入预览页面展示的内容条数,增加以下优化:
当导入数据量行数很大时,预览所有数据意义不大。
(1)找到路径:xadmin\plugins\importexport(xadmin包源码)
大概在156行处,可以找到ImportView视图;
再往下,在234行处:
result = resource.import_data(dataset, dry_run=True, raise_errors=False, file_name=import_file.name, user=request.user) context['result'] = result 后面增加: if len(result.rows) < 20: result_display = result.rows else: result_display = result.rows[:20] context['result_display'] = result_display context[‘result_display’]就是通过TemplateResponse传给模板展示预览数据。 (2)修改模板 找到路径:templates/xadmin/import_export/import.html(xadmin包源码) 在大约99行位置, 将{% for row in result.rows %}改成{% for row in result_display %}