django-import-export assign current user

旧巷老猫 提交于 2019-12-11 06:55:49

问题


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>>}


来源:https://stackoverflow.com/questions/50952887/django-import-export-assign-current-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!