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

2

9

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 ?

enter image description here

Resolute answered 29/8, 2017 at 3:52 Comment(0)
L
19

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()]
Lasonyalasorella answered 29/8, 2017 at 7:14 Comment(3)
This works very nice. Thanks! This has to be done in each admin class for each model for every app in the project. I wish there was a global setting.Resolute
You can make it a global setting very easily; you just have to modify the main ExportMixin class and read the formats from settings, or if there are no settings, use the defaults.Lasonyalasorella
You can also create your own mixin with this behavior, inherit from ExportMixin, and use your custom mixin to configure export, instead of the default oneInviolable
S
7

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
Sunfast answered 27/11, 2019 at 23:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.