django-import-export assign current user

2019-08-09 03:04发布

问题:

Trying to assign added_by user while creating an instance and want to create another model instance referring to the current instance

views.py

class ImportFarmersView(APIView):
    parser_classes = (MultiPartParser,)

    def post(self,request,org_slug=None,format=None,*args,**kwargs):
        serializer=TmpFileUploadSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(data=serializer.errors,status=status.HTTP_400_BAD_REQUEST)
        entries=serializer.validated_data['file']

        profile_resource=ProfileResource()
        dataset=Dataset()
        imported_data = dataset.load(open(entries.temporary_file_path(),'rb').read(),'xls')
        result = profile_resource.import_data(dataset, dry_run=True)  # Test the data import

        if result.has_errors():
            return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
        profile_resource.import_data(dataset, dry_run=False)  # Actually import now

        return Response(status=status.HTTP_202_ACCEPTED)

resources.py

class ProfileResource(resources.ModelResource):
    created_at=fields.Field(readonly=True)
    updated_at=fields.Field(readonly=True)
    class Meta:
        model=Profile
        skip_unchange=True
        report_skipped=False
        import_id_fields=('slug','email')

Thanks in advance

回答1:

You can access the current django user in the before_import_row hook on resources.ModelResource. There's a 'user' in **kwarg.

So in your case it would look something like

class ProfileResource(resources.ModelResource):
    ...
    def before_import_row(self, row, **kwargs):
        row['added_by'] = kwargs['user'].id

If you drop a breakpoint() in there and have a look at kwargs you'll see something like this (note that the User record is wrapped in a SimpleLazyObject):

-> row['added_by'] = kwargs['user'].id
(Pdb) kwargs
{'file_name': 'ImportDatasetWorking.csv', 'user': <SimpleLazyObject: <User: 
Kumar>>}