Search code examples
pythondjangodynamicfielddjango-import-export

Select which fields to export in django-import-export


I'm adding the django-import-export to the admin in my app.

One thing I wanted to do was to offer the possibility of selecting in the admin page of selecting which fields to export.

I searched for this topic but I only came across two questions with no answers.

Is it possible to add the possibility to dynamically choose which fields to export from the admin page?

Thanks.


Solution

  • Yes this is achievable, but it is a little tricky. Take a look at the example application, and get this working first.

    1. Take a look at the BookAdmin implementation.
    2. Create a subclass of ExportForm, which implements a form widget which can read the list of fields to export.
    3. Add a BookResource constructor which can take a form_fields as a kwarg, and save this as an instance variable.
    4. In BookAdmin, Override get_export_resource_kwargs() methods to return the list of fields from the form.
    5. Override get_export_fields() of BookResource to return the list of fields extracted from your form.
    6. Finally, you'll have to override export_action() so that it creates an instance of your custom form. (You actually only need to override the line which instantiates the form - there should be a get_export_form() method for this, so that the whole method doesn't need to be overridden. Feel free to submit a PR.)

    Try this out with the example application before porting to your own app.

    Example:

    (based on admin.py)

    class BookResource(ModelResource):
    
        class Meta:
            model = Book
    
        def __init__(self, form_fields=None):
            super().__init__()
            self.form_fields = form_fields
    
        def get_export_fields(self):
            return [self.fields[f] for f in self.form_fields]
    
    
    class BookExportForm(ExportForm):
        pass
        # Add your logic to read fields from the form
    
    
    class BookAdmin(ImportExportMixin, admin.ModelAdmin):
        list_display = ('name', 'author', 'added')
        list_filter = ['categories', 'author']
        resource_class = BookResource
    
        def get_export_resource_kwargs(self, request, *args, **kwargs):
            formats = self.get_export_formats()
            form = BookExportForm(formats, request.POST or None)
            # get list of fields from form (hard-coded to 'author' for example purposes)
            form_fields = ("author",)
            return {"form_fields": form_fields}