I am using Django Import-Export library to manage export functionalities in my Django admin interface. I have a requirement where I need to dynamically change the resource class based on the user's group membership.
Here's a simplified version of what I am trying to achieve:
from import_export.admin import ImportExportModelAdmin
from django.contrib import admin
from .resources import RawFileDMDResource, RawFileResource
class RawFileAdmin(ImportExportModelAdmin):
resource_class = RawFileResource
[...]
def get_resource_class(self, request=None):
resource_class = self.resource_class
if request is None:
user = get_user()
else:
user = request.user
if user.groups.filter(name='DMD ext_users').exists():
resource_class = RawFileDMDResource
return resource_class
However, the get_resource_class method expects a request argument. It seems that the Import-Export library doesn't provide the request object in the context of this method.
Is there a way to access the current user's information or request object within the get_resource_class method without explicitly passing the request object?
Unfortunately it is not easy to do this with the current codebase.
One option would be to override the entire export_action()
method so that you can add code to make selections based on the request
instance.
For example, you could pass the request into get_export_resource_classes()
.
You can then override get_export_resource_classes()
and add your selection logic there.
It would be a lot easier to return a Resource class based on request properties if this were passed into the method. I have raised an issue for this to be implemented. Feel free to submit a PR if you use this approach.
UPDATE
v4 of django-import-export will have the request instance passed into get_export_resource_classes()
, therefore this will be trivial to implement.