django import_export 个性化导出 model 里的 字段含有 choice 的值

December 17, 2023
测试
测试
测试
测试
11 分钟阅读

models.py

class UserProfile(AbstractUser):
    """
    用户
    """
    gender_choice = (
        ("0", "女"),
        ("1", "男"),
    )

    email = models.EmailField(verbose_name='邮箱', max_length=255, unique=True)
    phone = models.CharField(verbose_name="手机号码", max_length=50, unique=True, null=True, blank=True)
    avatar = models.URLField(verbose_name="用户头像", default="https://img.uali.cn/20231215/avatar_default.png")
    gender = models.CharField(max_length=32, choices=gender_choice, default="1", verbose_name="性别")
    time_black = models.DateTimeField(verbose_name="下次可访问时间", blank=True, null=True)
    last_ip = models.GenericIPAddressField(verbose_name="上次访问IP", default="0.0.0.0")

    class Meta:
        verbose_name = "用户信息"
        verbose_name_plural = "用户信息列表"

    def __str__(self):
        return "%s-%s %s" % (self.username[0].upper(), self.last_name, self.first_name)

admins.py

from django.contrib import admin
from apps.users.models import UserProfile
from django.utils.translation import ugettext as _
from django.contrib.auth.forms import (UserChangeForm, )
from .forms import UserCreationForm
from django.contrib.auth import get_user_model

import tablib
from import_export.admin import ImportExportActionModelAdmin
from import_export.widgets import ForeignKeyWidget
from import_export import resources, fields

User = get_user_model()


# Register your models here.

class UserResource(resources.ModelResource):

    def __init__(self, input_contract=None):
        super(UserResource, self).__init__()
        field_list = User._meta.fields
        self.verbose_name_dict = {}
        for i in field_list:
            self.verbose_name_dict[i.name] = i.verbose_name

    # 默认导入导出field的column_name为字段的名称,这里修改为字段的verbose_name
    def get_export_fields(self):
        fields = self.get_fields()
        for field in fields:
            field_name = self.get_field_name(field)
            # 如果有设置 verbose_name,则将 column_name 替换为 verbose_name, 否则维持原有的字段名。
            if field_name in self.verbose_name_dict.keys():
                field.column_name = self.verbose_name_dict[field_name]
        return fields

    def export(self, queryset=None, *args, **kwargs):
        """
        Exports a resource.
        """

        self.before_export(queryset, *args, **kwargs)

        if queryset is None:
            queryset = self.get_queryset()
        headers = self.get_export_headers()
        data = tablib.Dataset(headers=headers)

        gender_choice = {
            "0": "女",
            "1": "男",
        }

        for obj in self.iter_queryset(queryset):
            # 个性化显示 choice 的值
            # obj.gender = gender_choice[obj.gender]
            obj.gender = obj.get_gender_display()
            data.append(self.export_resource(obj))

        self.after_export(queryset, data, *args, **kwargs)

        return data

    class Meta:
        skip_unchanged = True  # 是否跳过的记录出现在导入结果对象
        report_skipped = False  # 所有记录将被导入
        # export_order = ('id', )
        model = User


# class UserProfileAdmin(admin.ModelAdmin):
class UserProfileAdmin(ImportExportActionModelAdmin):
    list_display = (
        'username', 'email', 'phone', 'last_name', 'first_name', 'is_active', 'is_staff', 'is_superuser')
    list_display_links = ('username', 'email', 'phone')
    list_editable = ['is_active', 'is_staff', 'is_superuser']
    # readonly_fields = ['password', ]

    # def get_model_form(self, **kwargs):
    #     """
    #     1.把 django UserCreationForm 拷贝出来修改成自己想要的
    #     2.修改 xadmin 继承表格,改成一步骤的表单
    #     :param kwargs:
    #     :return:
    #     """
    #     if self.org_obj is None:
    #         self.form = UserCreationForm
    #     else:
    #         self.form = UserChangeForm
    #     return super(UserProfileAdmin, self).get_model_form(**kwargs)
    resource_class = UserResource
    
    # 自定义导出的文件名,源码不支持中文名称,导入 urllib.parse,quote 下就能支持中文
    def get_export_filename(self, request, queryset, file_format):
        import urllib.parse
        date_str = datetime.datetime.now().strftime('%Y-%m-%d')
        # 蚂蚁金选基金数据_好买基金
        # filename_diy = "Funds_MaYi_JinXuan_From_HowBuy"
        filename_diy = urllib.parse.quote("蚂蚁金选基金数据_来自好买")
        filename = "%s_%s.%s" % (filename_diy, date_str, file_format.get_extension())
        # print(filename)
        return filename


admin.site.register(UserProfile, UserProfileAdmin)

继续阅读

更多来自我们博客的帖子

如何安装 BuddyPress
由 测试 December 17, 2023
经过差不多一年的开发,BuddyPress 这个基于 WordPress Mu 的 SNS 插件正式版终于发布了。BuddyPress...
阅读更多
Filter如何工作
由 测试 December 17, 2023
在 web.xml...
阅读更多
如何理解CGAffineTransform
由 测试 December 17, 2023
CGAffineTransform A structure for holding an affine transformation matrix. ...
阅读更多