Django Admin import_export module used for custom IMPORT
Asked Answered
T

1

2

I was trying to follow official doc of import-export:

https://django-import-export.readthedocs.org/en/latest/import_workflow.html#import-data-method-workflow

But I still do not know how to glue it to my admin assuming that:

  1. I want only subset of fields (I created Resource model with listed fields, but It crashes while importing anyway with: KeyError full stack bellow.

  2. Where - in which method - in my admin class (inheriting of course ImportExportModelAdmin and using defined resource_class) should i place the code responsible for some custom actions I want to happen after validating, that import data are correct but before inserting them into database.

I am not very advanced in Django and will be thankful for some hints. Example of working implementation will be appreciated, so if you know something similar on github - share.

Thermit answered 26/3, 2014 at 8:34 Comment(1)
1. please post stack trace, there is probably some typo 2. in resource_class you can override some methods (which are listed in import_workflow)Brey
C
0

you can override it as

to create a new instance

def get_instance(self, instance_loader, row):
    return False

your custom save

def save_instance(self, instance, real_dry_run):
    if not real_dry_run:
            try:
                obj = YourModel.objects.get(some_val=instance.some_val)
                # extra logic if object already exist
            except NFCTag.DoesNotExist:
                # create new object
                obj = YourModel(some_val=instance.some_val)
                obj.save()

def before_import(self, dataset, dry_run):

    if dataset.headers:
        dataset.headers = [str(header).lower().strip() for header in dataset.headers]

      # if id column not in headers in your file
    if 'id' not in dataset.headers:
        dataset.headers.append('id')
Crafty answered 27/3, 2015 at 8:14 Comment(1)
Arrived here with a related problem, but as best I can tell just appending "id" to the headers doesn't instantiate a blank column and cause import_export to create new records and auto-increment the integer pk. Appending a full column of None values works (dataset.append_col([None for row in range(len(dataset))], header = 'id'), though that may not be the most elegant solution.Cai

© 2022 - 2024 — McMap. All rights reserved.