我正在使用Django 2.x
和Django-import-export在管理面板中启用导入Excel文件。
app / models.py
class ChapterQuestion(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE)
word = models.CharField(max_length=250)
definition = models.CharField(max_length=250)
pronunciation = models.CharField(max_length=250, blank=True)
synonym = models.CharField(max_length=250, blank=True)
antonym = models.CharField(max_length=250, blank=True)
comment = models.CharField(max_length=250, blank=True, null=True)
app / admin.py
class ChapterQuestionResource(resources.ModelResource):
class Meta:
model = ChapterQuestion
fields = (
'chapter__course__name', 'chapter__name', 'word', 'definition',
'synonym', 'antonym', 'pronunciation', 'comment'
)
@admin.register(ChapterQuestion)
class ChapterQuestionAdmin(ImportExportModelAdmin):
resource_class = ChapterQuestionResource
exclude = ['created_by']
list_display = ['word', 'definition', 'chapter', 'get_chapter_course', 'created_by']
但是,当我导入.xls
文件时,它显示为(sample file)错误
Errors
Line number: 1 - 'id'
Hello, world, , , , , Test course 001, Chapter 001
Traceback (most recent call last):
File "/Users/anuj/.local/share/virtualenvs/django-vocab-899c1OSV/lib/python3.6/site-packages/import_export/resources.py", line 453, in import_row
instance, new = self.get_or_init_instance(instance_loader, row)
File "/Users/anuj/.local/share/virtualenvs/django-vocab-899c1OSV/lib/python3.6/site-packages/import_export/resources.py", line 267, in get_or_init_instance
instance = self.get_instance(instance_loader, row)
File "/Users/anuj/.local/share/virtualenvs/django-vocab-899c1OSV/lib/python3.6/site-packages/import_export/resources.py", line 261, in get_instance
return instance_loader.get_instance(row)
File "/Users/anuj/.local/share/virtualenvs/django-vocab-899c1OSV/lib/python3.6/site-packages/import_export/instance_loaders.py", line 31, in get_instance
field = self.resource.fields[key]
KeyError: 'id'
Line number: 2 - 'id'
hello, world, , this it, that thing, commets are welcome, Test course 001, Chapter 001
Traceback (most recent call last):
File "/Users/anuj/.local/share/virtualenvs/django-vocab-899c1OSV/lib/python3.6/site-packages/import_export/resources.py", line 453, in import_row
instance, new = self.get_or_init_instance(instance_loader, row)
File "/Users/anuj/.local/share/virtualenvs/django-vocab-899c1OSV/lib/python3.6/site-packages/import_export/resources.py", line 267, in get_or_init_instance
instance = self.get_instance(instance_loader, row)
File "/Users/anuj/.local/share/virtualenvs/django-vocab-899c1OSV/lib/python3.6/site-packages/import_export/resources.py", line 261, in get_instance
return instance_loader.get_instance(row)
File "/Users/anuj/.local/share/virtualenvs/django-vocab-899c1OSV/lib/python3.6/site-packages/import_export/instance_loaders.py", line 31, in get_instance
field = self.resource.fields[key]
KeyError: 'id'