Search code examples
django-import-export

Cannot Insert header using the before_import override function in django-import-export


I'm using django-import-export to upload csv files through django admin. I have the ability to override the before_import function to add functionality before the import. I have a csv file with no headers, and the actual data starts on line one. I need to add a header, or insert a row before my csv file is uploaded, so that it can be read properly.

class UpdateResource(resources.ModelResource):
    def before_import(self, dataset, using_transactions, dry_run, **kwargs):
        dataset.header = ['sku', 'quantity']

    class Meta:
        model = Upload
        import_id_fields = ('sku',)

This code changes the value of the first row of my csv file to sku,quantity, but I need to insert one above that value, not replace it. Alternatively, if there is an option to ignore headers and just map the values to my model from left to right or something, that would be great too.


Solution

  • My fix was to store the first row as a variable, create the desired header and append the first row to end of file.

    class UpdateResource(resources.ModelResource):
        def before_import(self, dataset, using_transactions, dry_run, **kwargs):
            first_row = dataset.header
            dataset.header = ['sku', 'quantity']
            dataset.append(first_row)