Django import-export如何将当前管理员用户添加到模型中

时间:2015-11-21 19:02:38

标签: python django django-import-export

我想让import-export选择当前/保存用户(在模型中定义为“作者”字段)

我试过这个(save_model)但它不起作用(我认为是因为资源类)

class KWResource(resources.ModelResource):

    class Meta:

        model = KW
        import_id_fields = ('Keyword',)
        fields = ('Keyword',)


    searchess = fields.Field(attribute='searches', column_name="Avg. Monthly Searches (exact match only)")
    compp = fields.Field(attribute='comp', column_name="Competition")
    cpcc = fields.Field(attribute='cpc', column_name="Suggested bid")        

    def save_model(self, request, obj, form, change):
        if getattr(obj, 'author', None) is None:
            obj.author = request.user
        obj.save()

如何获取在此处启动导入的管理员用户的ID?

2 个答案:

答案 0 :(得分:1)

想出来,不确定它是否是最佳解决方案,但它有效:

class KWResource(resources.ModelResource):
....
....
   def before_import(self, dataset, dry_run, *args, **kwargs):
       li = []
       li.append(kwargs.pop('user', 1))
       dataset.insert_col(0, li, 'user')
       return super(KWResource, self).before_import(dataset, dry_run, *args, **kwargs)

答案 1 :(得分:0)

对于以后发现此问题的任何人,您都可以在Resource的钩子中访问当前的django用户。 ** kwargs中有一个“用户”。

def before_import_row(self, row, **kwargs):
    row['author'] = kwargs['user'].id

此处有更多详细信息: django-import-export assign current user