Не знаю почему, но Django Command не может создать множество записей после чтения CSV-файла. Команда не работает локально или при размещении на Heroku.
Я использую библиотеку pandas для чтения данных CSV, но также использую кодирование ('utf-8').
Сначала это работало, но мне пришлось внести некоторые изменения в исходный файл, а после сохранения и создания:
python manage.py collectstatic
Я получаю ошибку при запуске команды:
python manage.py ubigeo_peru
Я решил эту проблему, импортировав файл как файл Excel, но все же
интересно, что не так с CSV.
tmp_data=pd.ExcelFile("static/data/ubigeo-peru.xlsx")
tmp_data=tmp_data.parse("ubigeo-peru")
Я также вижу, что ошибка кодирования появляется только на github при просмотре данных RAW:
https://raw.githubusercontent.com/OmarGonD/stickers_gallito/master/static/data/ubigeo-peru.csv
![enter image description here](https://i.stack.imgur.com/XKG2q.png)
ubigeo_peru.py
import pandas as pd
import csv
from shop.models import Peru
from django.core.management.base import BaseCommand
tmp_data=pd.read_csv('static/data/ubigeo-peru.csv',sep=',', encoding="utf-8")
# tmp_data=pd.read_csv('static/data/ubigeo-peru.csv',sep=',')
class Command(BaseCommand):
def handle(self, **options):
products = [
Peru(
departamento=row['departamento'],
provincia=row['provincia'],
distrito=row['distrito'],
costo_despacho_con_recojo=row['costo_despacho_con_recojo'],
costo_despacho_sin_recojo=row['costo_despacho_sin_recojo'],
dias_despacho = row['dias_despacho']
)
for idx, row in tmp_data.iterrows()
]
Peru.objects.bulk_create(products)
Данные выглядят хорошо на GitHub и когда открывается в Excel.
https://github.com/OmarGonD/stickers_gallito/blob/master/static/data/ubigeo-peru.csv
Ошибка при локальном или удаленном запуске команды:
$ python manage.py ubigeo_peru
D:\virtual_envs\stickers-gallito-app\lib\site-packages\requests\__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (3.0.4) doesn't match a supported version!
RequestsDependencyWarning)
Traceback (most recent call last):
File "pandas\_libs\parsers.pyx", line 1134, in pandas._libs.parsers.TextReader._convert_tokens
File "pandas\_libs\parsers.pyx", line 1240, in pandas._libs.parsers.TextReader._convert_with_dtype
File "pandas\_libs\parsers.pyx", line 1256, in pandas._libs.parsers.TextReader._string_convert
File "pandas\_libs\parsers.pyx", line 1494, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 0: invalid start byte
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 19, in <module>
execute_from_command_line(sys.argv)
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\django\core\management\__init__.py", line 224, in fetch_command
klass = load_command_class(app_name, subcommand)
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\django\core\management\__init__.py", line 36, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "C:\Users\OGONZALES\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\web_proyects\stickers-gallito-app\shop\management\commands\ubigeo_peru.py", line 8, in <module>
tmp_data=pd.read_csv('static/data/ubigeo-peru.csv',sep=',', encoding="utf-8")
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\pandas\io\parsers.py", line 678, in parser_f
return _read(filepath_or_buffer, kwds)
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\pandas\io\parsers.py", line 446, in _read
data = parser.read(nrows)
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\pandas\io\parsers.py", line 1036, in read
ret = self._engine.read(nrows)
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\pandas\io\parsers.py", line 1848, in read
data = self._reader.read(nrows)
File "pandas\_libs\parsers.pyx", line 876, in pandas._libs.parsers.TextReader.read
File "pandas\_libs\parsers.pyx", line 891, in pandas._libs.parsers.TextReader._read_low_memory
File "pandas\_libs\parsers.pyx", line 968, in pandas._libs.parsers.TextReader._read_rows
File "pandas\_libs\parsers.pyx", line 1094, in pandas._libs.parsers.TextReader._convert_column_data
File "pandas\_libs\parsers.pyx", line 1141, in pandas._libs.parsers.TextReader._convert_tokens
File "pandas\_libs\parsers.pyx", line 1240, in pandas._libs.parsers.TextReader._convert_with_dtype
File "pandas\_libs\parsers.pyx", line 1256, in pandas._libs.parsers.TextReader._string_convert
File "pandas\_libs\parsers.pyx", line 1494, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 0: invalid start byte
(stickers-gallito-app)