Nema Ga
Nema Ga

Reputation: 2590

Django import-export how to add current admin user to model

I am trying to make import-export select current/save user(defined as "author" field in model)

I tried this(save_model) but it doesn't work(I think because of resource class)

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()

How to get id of admin user that initiated import here?

Upvotes: 1

Views: 1893

Answers (2)

Jagu
Jagu

Reputation: 2561

For anyone finding this later, you can access the current django user in a hook on your Resource. There's a 'user' in the **kwargs.

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

More detail here: django-import-export assign current user

Upvotes: 2

Nema Ga
Nema Ga

Reputation: 2590

Figured it out, not sure if it's the best solution but it works:

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)

Upvotes: 2

Related Questions