简体   繁体   中英

how to import excel file with django import-export

I use django import-export and I can not import an excel file I get the error:

Line number: 1 - 'id'

Traceback (most recent call last):
File "C: \ mat4 \ env \ lib \ site-packages \ import_export \ resources.py", line 317, in import_data
instance = new self.get_or_init_instance (instance_loader, row)
File "C: \ mat4 \ env \ lib \ site-packages \ import_export \ resources.py", line 149, in get_or_init_instance
instance = self.get_instance (instance_loader, row)
KeyError: 'id'

Line number: 2 - 'id'

Traceback (most recent call last):
File "C: \ mat4 \ env \ lib \ site-packages \ import_export \ resources.py", line 317, in import_data
instance = new self.get_or_init_instance (instance_loader, row)
File "C: \ mat4 \ env \ lib \ site-packages \ import_export \ resources.py", line 149, in get_or_init_instance
instance = self.get_instance (instance_loader, row)
KeyError: 'id'

my model:

class Essai_Temperature(models.Model):
name = models.ForeignKey(Material, verbose_name=_('name'))                                    
nature_unit = models.ForeignKey(Property, verbose_name=_('category'))                      
choix = ChainedForeignKey(Physic, verbose_name=_('properties'), null=True, blank=True,
                          related_name='Essai_Temperature_choix',
                          chained_field="nature_unit",
                          chained_model_field="name",
                          show_all=False,
                          auto_choose=True) 
valT= models.FloatField(_('temperature'),blank=True, null=False)   
val10= models.FloatField(_('value'), blank=True, null=False)                                               
val_ref= models.CharField(_('reference of the data'), max_length=50, default='0')                  

resources.py

class Essai_Temperature_Resource(resources.ModelResource):
class Meta(object):
    model = Essai_Temperature

admin.py

class Essai_TemperatureAdmin(ImportExportModelAdmin):
resource_class = Essai_Temperature_Resource 
list_display = ('name', 'nature_unit', 'choix', 'valT', 'val10', 'val_ref')
ordering = ('name__name', 'nature_unit__name', 'choix__lapropriete', 'valT',)
list_filter = ('name', 'nature_unit', 'choix')

and excel file

1   CT55    Mechanical  Hardness - Vickers (Mpa)    44  125 EF-01

2   CT55    Mechanical  Hardness - Vickers (Mpa)    44  127 EF-02

I do not understand the problem with the 'id' ?

django-import-export希望标题行知道如何将列映射到字段。

By default django import export expects the primary key 'id' on your column headings.

You can change this behavior by changinf your resources.py to

class Essai_Temperature_Resource(resources.ModelResource):
     class Meta(object):
     model = Essai_Temperature
     import_id_fields = ('<your key field here>',)

This is an older question, but I got hung up on this same thing and didn't find a clear answer so I'm going to attempt that now.

You didn't share the code you were using to do the actual import so I will assume for the sake of this answer that you have a file called c:\\import\\data.xls. Also your file has to have a header row.

import os
import tablib
from import_export import resources


dataset = tablib.Dataset()   # We need a dataset object
Essai_Temperature_Resource = resources.modelresource_factory(model=Essai_Temperature)()
file = 'c:\import\data.xls'
dataset.xls = open(file).read()

# Add a blank ID column to each row.
dataset.insert_col(0, col=[None,], header="id")

# Do a Dry-Run and see if anything fails
result = Essai_Temperature_Resource.import_data(dataset, dry_run=True)
if (result.has_errors()):
    print(result)  # What is the error?
else:
    # If there were no errors do the import for real
    result = Essai_Temperature_Resource.import_data(dataset, dry_run=False)

When I did this, I was using a CSV file and I don't know 100% for sure the xls works the same, but I'm assuming it does.

Also, for me, when I first ran this, I got an "invalid dimensions" error. The reason for that (for me) was that I had a blank line at the end of my file. When I stripped that off it all worked great.

I hope that helps those who come next looking for this same answer.

"Format None cannot be imported." error for csv file is fixed as follows:

imported_data = dataset.load(inventory.read().decode('utf-8'),format='csv')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM