天天看點

xadmin importexport插件使用過程出現的問題記錄

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

.

解決辦法:

将import_export/resources.py 的

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 %}