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
Solution 1:
Yes this is achievable, but it is a little tricky. Take a look at the example application, and get this working first.
- Take a look at the
BookAdmin
implementation. - Create a subclass of
ExportForm
, which implements a form widget which can read the list of fields to export. - Add a
BookResource
constructor which can take aform_fields
as a kwarg, and save this as an instance variable. - In
BookAdmin
, Overrideget_export_resource_kwargs()
methods to return the list of fields from the form. - Override
get_export_fields()
ofBookResource
to return the list of fields extracted from your form. - 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 aget_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
)
classBookResource(ModelResource):
classMeta:
model = Book
def__init__(self, form_fields=None):
super().__init__()
self.form_fields = form_fields
defget_export_fields(self):
return [self.fields[f] for f in self.form_fields]
classBookExportForm(ExportForm):
pass# Add your logic to read fields from the formclassBookAdmin(ImportExportMixin, admin.ModelAdmin):
list_display = ('name', 'author', 'added')
list_filter = ['categories', 'author']
resource_class = BookResource
defget_export_resource_kwargs(self, request, *args, **kwargs):
formats = self.get_export_formats()
form = BookExportForm(formats, request.POST orNone)
# get list of fields from form (hard-coded to 'author' for example purposes)
form_fields = ("author",)
return {"form_fields": form_fields}
Post a Comment for "Select Which Fields To Export In Django-import-export"