Using django-import-export: How to customise which fields to export Excel files

I just starting out using Django. I'm using django-import-export package and I tried to customize my Django admin panel in this page in order to choose which fields to export to excel file.

Here is my admin model

    class CompanyAdmin(ImportExportMixin, admin.ModelAdmin):

        model = Company
        resource_classes = [CompanyResource]
        list_display = [
        fields = [
        def get_export_resource_kwargs(self, request, *args, **kwargs):
            formats = self.get_export_formats()
            form = CompanyExportForm(formats, request.POST or None)
            form_fields = ("name", "email", ) 
            return {"form_fields": form_fields}

Here is my model resource

class CompanyResource(resources.ModelResource):
    class Meta:
        model = Company
    def __init__(self, form_fields=None):
        self.form_fields = form_fields

    def get_export_fields(self):
        return [self.fields[f] for f in self.form_fields]

Here is my export form

class CompanyExportForm(ExportForm):

    # what should i write here? is this the place that i should write the custom code eg: checkboxes where user have the options to export the 'name` or 'email' fields ??

I try to use the same way as in this post in order to achieve the same result. However, i have been stuck forever.

If you want to define which fields should be exported, refer to this post. This means that only those fields will be exported, and the user cannot choose. This is relatively simple to achieve.

However it seems like you want the user to be able to choose the fields in the UI, then it is more complicated, and will involve more customisation. The answer you link to is the starting point.

There will have to be some UI element in which the user can choose the fields for export (e.g. some multi select widget). Then on POST, you'll have to read the ids of those fields and then feed that into the export() method.

If you are new to Django, it's going to take a bit of work to implement, and will be quite a steep learning curve. If you can find a "clean" way to implement it, such that future users would be able to implement, we would consider a PR.

Back to Top