Bru*_*uce 5 csv django python-3.x
我想上传csv文件并存储在数据库中.当我单击提交按钮时,我收到以下错误
Environment:
Request Method: POST
Request URL: http://localhost:8000/csv
Django Version: 1.9
Python Version: 3.4.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'django.contrib.admindocs',
'world',
'pft',
'wms',
'djgeojson',
'html5',
'geoexplorer']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "C:\Python34\Lib\site-packages\django\bin\geodjango\pft\views.py" in add_multiple_accounts
95. csv_result, rows_error = utils.handle_uploaded_file(file, utils.account_valid_fields, utils.create_account_in_db)
File "C:\Python34\Lib\site-packages\django\bin\geodjango\pft\utils.py" in handle_uploaded_file
24. if not valid_fields_method(data.fieldnames):
File "C:\Python34\lib\csv.py" in fieldnames
96. self._fieldnames = next(self.reader)
Exception Type: Error at /csv
Exception Value: iterator should return strings, not bytes (did you open the file in text mode?)
Run Code Online (Sandbox Code Playgroud)
我的句柄文件上传功能低于-utils.py
def handle_uploaded_file(file, valid_fields_method, record_creation_function):
file.seek(0)
sniffdialect = csv.reader(codecs.iterdecode(file, 'utf-8')
file.seek(0)
data = csv.DictReader(file, dialect=sniffdialect)
if not valid_fields_method(data.fieldnames):
return False, -1
result, rows_error = record_creation_function(data)
return result, rows_error
Run Code Online (Sandbox Code Playgroud)
我正在使用django 1.9和python 3.4.请帮忙 !我挣扎了两天.
改变这个:
file.seek(0)
sniffdialect = csv.reader(codecs.iterdecode(file, 'utf-8')
file.seek(0)
data = csv.DictReader(file, dialect=sniffdialect)
Run Code Online (Sandbox Code Playgroud)
对此:
file.seek(0)
data = csv.DictReader(codecs.iterdecode(file, 'utf-8'))
Run Code Online (Sandbox Code Playgroud)
(顺便说一句,我会检查是否seek(0)真的需要.)
您已了解需要解码文件中的内容,这是正确的.但是,这样做,你正在使用dialect,这是错误的.
dialect不适合这种东西.此外,它应该是通过注册的名称csv.register_dialect(),而不是任意迭代器.但无论如何,方言在这里无法帮助你.
相反,您应该将解码后的流直接传递给DictReader.
| 归档时间: |
|
| 查看次数: |
1686 次 |
| 最近记录: |