Home > Enterprise >  Incorrect csv format when using ImportExportModelAdmin
Incorrect csv format when using ImportExportModelAdmin

Time:04-14

I'm trying to upload the csv file below but it's only uploading some columns and then some of those values are empty. Prior to this, I was receiving a error:

```  self.fields[f] for f in self.get_import_id_fields()
KeyError: 'id'``` 

which I fixed by using advice from wrong data import

CodePudding user response:

Ok, I see now. The reason why the values aren't populating the columns is because your CSV file has the column names with spaces instead of underscores. You have 2 options:

  1. (Quick and easy) Change the CSV column names to reflect the attribute names defined in your model. E.g. Customer ID would become customer_id and Customer Name would be customer_name.

    You probably also want to lowercase your Latitude and Longitude column names.

  2. (Requires some extra code) Manually define the column name in your resource by mapping the attribute of the model to the column in the CSV. E.g.:

    from import_export.fields import Field
    
    class PropertyAdminResource(resources.ModelResource):
    
        customer_id = Field(
            attribute="customer_id",
            column_name="Customer ID",
        )
        customer_name = Field(
            attribute="customer_name",
            column_name="Customer Name"
        )
    
        class Meta:
            model = Customer
            fields = (
                'customer_id',
                'customer_name',
                'latitude',
                'longitude',
                'town',
                'region',
                'country',
            )
            import_id_fields = ('customer_id',)
    
  • Related