django-import-export: question:UnicodeDecodeError at /admin/blog/author/import/

Sir,thanks a lot to develop this great repository. I have little problem to solve , as below the code:

#in models.py
class Author(models.Model):
    author = models.CharField('作者', max_length=50)
    title = models.CharField('标题', max_length=150)
    qualification = models.ForeignKey(Qualification)
    mark = models.ManyToManyField(Mark)
    blog = models.TextField('博客内容')
    time = models.DateField('写作日期')

    def __unicode__(self):
        return unicode(self.author)

    class Meta:
        ordering = ['time']
#in admin.py
class AuthorAdmin(ImportExportModelAdmin, admin.ModelAdmin):
    search_fields = ('author', 'title', 'mark', 'blog')
    list_display = ('author', 'title', 'time')

When I export the data, 1 but the csv file appear to be the retortion, 2 when I modified the second row author data and import,

3 it cause the error, 4

how I it be smoothly modified and import?thanks. Allenlee

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 31 (15 by maintainers)

Most upvoted comments

Hi guys,

I’ve stumbled upon the exact same issue in one of my company’s projects. We’re using python3 and I’m 100% sure there’s no u’ missing on any model’s __ str__ method. Yet, the UnicodeDecodeError exception still occurs when trying to import a csv file containing utf-8 encoded characters in the django admin.

It turns out that adding the encoding param with value of utf-8 to the TempFolderStorage.open’s method seems to solve the problem, at least in our environment.

Here’s a quick’n’dirty fix in case anyone googles this issue trying to find a solution, like I did a few hours ago.

First we subclass the TempFolderStorage class, adding said param:

import tempfile
from import_export.tmp_storages import TempFolderStorage

class Utf8TempFolderStorage(TempFolderStorage):

    def open(self, mode='r'):
        if self.name:
            return open(self.get_full_path(), mode, encoding='utf-8')
        else:
            tmp_file = tempfile.NamedTemporaryFile(delete=False)
            self.name = tmp_file.name
            return tmp_file

Then we point the new class as IMPORT_EXPORT_TMP_STORAGE_CLASS in settings.py:

 IMPORT_EXPORT_TMP_STORAGE_CLASS = 'path.to.storages.Utf8TempFolderStorage'