I was looking for something similar. I wanted the request object, based on the request made in the admin to export, to be attached to the Resource instance so I could inspect it and dynamically affect functionality based on query parameters. This would also be very useful if you wanted to change it dynamically based on User. It ended up being quite simple:
First, subclass the ModelResource class and look for a new kwarg:
from import_export import resources
class RequestModelResource(resources.ModelResource):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(RequestModelResource, self).__init__(*args, **kwargs)
Then, there is a relevant admin method in import-export you can use to pass kwargs. See here. Add this to your ModelAdmin that inherits from import_export.admin.ImportExportModelAdmin
:
class MyModelAdmin(ImportExportModelAdmin):
resource_class = MyModelResource
def get_resource_kwargs(self, request, *args, **kwargs):
""" Passing request to resource obj to control exported fields dynamically """
return {'request': request}
That's basically it. Use the request now wherever you want in Resource classes that inherit from RequestModelResource. For example:
class MyModelResource(RequestModelResource):
def get_export_fields(self):
fields = super().get_fields()
# Check self.request.user, self.request.GET, etc to impact logic
# however you want!
return fields
django-import-export
, but have you triedself.request
? – Gummget_queryset
method and inspect stacktrace. Somewhere in the stacktrace there will be a request and you can see how is it going toModelResource
– Gumm