xadmin引入django-import-export导入功能
一、安装
由于xadmin自带的包里面已经包含了django-import-export
所以不用再pip install django-import-export了
但是xadmin管理后台只有导出按钮
没有导入按钮
所以本次引入了导入功能
二、配置文件
demo/settings.py:
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
三、复制资源文件
python manage.py collectstatic
拷贝静态文件
此时static目录下新增了static/import_export目录
四、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)
五、xadmin管理后台
python manage.py runserver
启动服务
六、优化
以上这样有2个弊病
Excel文件列名与导入预览页面列名都是字段英文名称
而不是verbose_name中文名称
很不方便
修改product/admin.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 = (
'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']
# 要展示详情的字段
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)
分类:
Django(Python3)
标签:
django
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2018-08-18 Python拼接字符串的7种方法