xadmin引入django-import-export導入功能

1、安裝python

因爲xadmin自帶的包裏面已經包含了django-import-exportmysql

因此不用再pip install django-import-exportsql

可是xadmin管理後臺只有導出按鈕數據庫

沒有導入按鈕django

因此本次引入了導入功能session

 

 

2、配置文件app

demo/settings.pyide

 

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'db@02^k!pw$6kx*0$+9#%2h@vro-*h^+xs%5&(+q*b181&o$)l'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'product.apps.ProductConfig',

'xadmin',
'crispy_forms',
'reversion',
# 添加django-xadmin

'import_export',
# 導入導出
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'demo.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'demo.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'demo',
'HOST': '192.168.1.106',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'Abcdef@123456',
}
}
# MySQL數據庫配置


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'zh-hans'
# 簡體中文界面

TIME_ZONE = 'Asia/Shanghai'
# 亞洲/上海時區

USE_I18N = True

USE_L10N = True

USE_TZ = False
# 不使用國際標準時間


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# 定義靜態文件的目錄

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# 定義圖片存放的目錄

IMPORT_EXPORT_USE_TRANSACTIONS = True
# 在導入數據時使用數據庫事務,默認False

 

 

3、複製資源文件測試

python manage.py collectstatic優化

拷貝靜態文件

 

此時static目錄下新增了static/import_export目錄

 

 

4、Admin後臺註冊

product/admin.py

import xadmin

# Register your models here.
from import_export import resources
from xadmin import views

from product.models import ProductInfo


class ProductInfoResource(resources.ModelResource):

class Meta:
model = ProductInfo

skip_unchanged = True
# 導入數據時,若是該條數據未修改過,則會忽略
report_skipped = True
# 在導入預覽頁面中顯示跳過的記錄

import_id_fields = ('id',)
# 對象標識的默認字段是id,您能夠選擇在導入時設置哪些字段用做id

fields = (
'id',
'product_name',
'product_picture',
'product_describe',
'product_manager',
)
# 白名單

exclude = (
'create_time',
'update_time',
)
# 黑名單


class ProductInfoAdmin(object):
list_display = [
'id',
'product_name',
'product_picture',
'product_describe',
'product_manager',
'create_time',
'update_time',
]
# 要顯示的字段列表

ordering = ['id']
# 按照id順序排列,若是是倒序-id

search_fields = ['product_name', 'product_manager']
# 要搜索的字段

list_filter = ['product_name', 'create_time', 'update_time']
# 要篩選的字段

show_detail_fields = ['product_name', 'product_picture']
# 要展現詳情的字段

list_editable = ['product_name', 'product_picture',
'product_describe', 'product_manager']
# 列表可直接修改的字段

list_per_page = 10
# 分頁

# model_icon = 'fa fa-laptop'
# 配置模型圖標,也能夠在GlobalSetting裏面配置

import_export_args = {
'import_resource_class': ProductInfoResource,
# 'export_resource_class': ProductInfoResource,
}
# 配置導入按鈕


class BaseSetting(object):
enable_themes = True
use_bootswatch = True
# 開啓主題自由切換


class GlobalSetting(object):
global_search_models = [ProductInfo]
# 配置全局搜索選項,默認搜索組、用戶、日誌記錄
site_title = "測試平臺"
# 標題
site_footer = "測試部"
# 頁腳

menu_style = "accordion"
# 左側菜單收縮功能
apps_icons = {
"product": "fa fa-music",
}
# 配置應用圖標,即一級菜單圖標
global_models_icon = {
ProductInfo: "fa fa-film",
}
# 配置模型圖標,即二級菜單圖標


xadmin.site.register(ProductInfo, ProductInfoAdmin)
# 註冊模型

xadmin.site.register(views.BaseAdminView, BaseSetting)
xadmin.site.register(views.CommAdminView, GlobalSetting)

 

 

5、xadmin管理後臺

python manage.py runserver

啓動服務

http://127.0.0.1:8000/admin/

 

6、優化

以上這樣有2個弊病

Excel文件列名與導入預覽頁面列名都是字段英文名稱

而不是verbose_name中文名稱

很不方便

 

 

 

修改product/models.py:

import xadmin

# Register your models here.
from import_export import resources
from xadmin import views
from xadmin.layout import Main, Fieldset, Side

from product.models import ProductInfo

from django.apps import apps


class ProductInfoResource(resources.ModelResource):

def __init__(self):
super(ProductInfoResource, self).__init__()
field_list = apps.get_model('product', 'ProductInfo')._meta.fields
# 應用名與模型名
self.verbose_name_dict = {}
# 獲取全部字段的verbose_name並存放在verbose_name_dict字典裏
for i in field_list:
self.verbose_name_dict[i.name] = i.verbose_name

def get_export_fields(self):
fields = self.get_fields()
# 默認導入導出field的column_name爲字段的名稱
# 這裏修改成字段的verbose_name
for field in fields:
field_name = self.get_field_name(field)
if field_name in self.verbose_name_dict.keys():
field.column_name = self.verbose_name_dict[field_name]
# 若是設置過verbose_name,則將column_name替換爲verbose_name
# 不然維持原有的字段名
return fields

class Meta:
model = ProductInfo

skip_unchanged = True
# 導入數據時,若是該條數據未修改過,則會忽略
report_skipped = True
# 在導入預覽頁面中顯示跳過的記錄

import_id_fields = ('id',)
# 對象標識的默認字段是id,您能夠選擇在導入時設置哪些字段用做id

fields = (
'id',
'product_name',
'product_picture',
'product_describe',
'product_manager',
)
# 白名單

exclude = (
'product_detail',
'create_time',
'update_time',
)
# 黑名單


class ProductInfoAdmin(object):

list_display = [
'id',
'product_name',
'product_picture',
'product_describe',
'product_manager',
'product_detail',
'create_time',
'update_time',
]
# 要顯示的字段列表

ordering = ['id']
# 按照id順序排列,若是是倒序-id

search_fields = ['product_name', 'product_manager']
# 要搜索的字段

list_filter = ['product_name', 'create_time', 'update_time']
# 要篩選的字段

show_detail_fields = ['product_name', 'product_detail']
# 要展現詳情的字段

list_editable = ['product_name', 'product_describe', 'product_manager']
# 列表可直接修改的字段

list_per_page = 10
# 分頁

# model_icon = 'fa fa-laptop'
# 配置模型圖標,也能夠在GlobalSetting裏面配置

import_export_args = {
'import_resource_class': ProductInfoResource,
# 'export_resource_class': ProductInfoResource,
}
# 配置導入按鈕


class BaseSetting(object):
enable_themes = True
use_bootswatch = True
# 開啓主題自由切換


class GlobalSetting(object):
global_search_models = [ProductInfo]
# 配置全局搜索選項,默認搜索組、用戶、日誌記錄
site_title = "測試平臺"
# 標題
site_footer = "測試部"
# 頁腳

menu_style = "accordion"
# 左側菜單收縮功能
apps_icons = {
"product": "fa fa-music",
}
# 配置應用圖標,即一級菜單圖標
global_models_icon = {
ProductInfo: "fa fa-film",
}
# 配置模型圖標,即二級菜單圖標


xadmin.site.register(ProductInfo, ProductInfoAdmin)
# 註冊模型

xadmin.site.register(views.BaseAdminView, BaseSetting)
xadmin.site.register(views.CommAdminView, GlobalSetting)

相關文章
相關標籤/搜索