How to have only CSV, XLS, XLSX options in django-import-export?

南笙酒味 提交于 2019-12-31 01:19:06

问题


I have implemented django-import-export for my project.

It provides me many file format options by default fro both import and export.

How to restrict the file formats to only CSV, XLS and XLSX ?


回答1:


You can override the get_export_formats() method of the ExportMixin:

from import_export.formats import base_formats


class MyAdmin(ExportMixin):
    # your normal stuff
    def get_export_formats(self):
            """
            Returns available export formats.
            """
            formats = (
                  base_formats.CSV,
                  base_formats.XLS,
                  base_formats.XLSX,
                  base_formats.TSV,
                  base_formats.ODS,
                  base_formats.JSON,
                  base_formats.YAML,
                  base_formats.HTML,
            )
            return [f for f in formats if f().can_export()]



回答2:


This is old, but for those who might like to know...I can't comment above because I don't have "50 reputation". To extend Burhan Khalid's answer above, if you'd like to apply these format restrictions (or any overwritten methods of ExportMixin to multiple admin classes) you can create an abstract base class in the admin and then use that class for the classes you'd like to keep those overwrites.

from import_export.formats import base_formats

# use for all admins that are admin.ModelAdmin and use ExportMixin
class ExportMixinAdmin(ExportMixin, admin.ModelAdmin):

    # your normal stuff

    def get_export_formats(self):
        formats = (
          base_formats.CSV,
          base_formats.XLS,
          base_formats.XLSX,
          )

        return [f for f in formats if f().can_export()]

    class Meta:
        abstract = True

class ModelOneAdmin(ExportMixinAdmin):

    # your normal stuff here

class ModelTwoAdmin(ExportMixinAdmin):

    # your normal stuff here


来源:https://stackoverflow.com/questions/45930421/how-to-have-only-csv-xls-xlsx-options-in-django-import-export

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!