V
V
Viktor Yurchenko2019-02-02 17:42:02
Django
Viktor Yurchenko, 2019-02-02 17:42:02

IndexError: list index out of range when trying to load csv file into model what is the reason?

# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from fcapp.models import Distributor
import csv


class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('csv_file', nargs='+', type=str)

    def handle(self, *args, **options):
        for csv_file in options['csv_file']:
            dataReader = csv.reader(open(csv_file), delimiter=',', quotechar='"')
            for row in dataReader:
                emp = Distributor()
                emp.name = row[0]
                emp.full_name = row[0]
                emp.address = row[1]
                emp.phone = '{0} {1}'.format(row[2],row[3])
                emp.email = row[4]
                emp.site = row[5]
                emp.api_key= 'uniqkey'
                emp.language = 'ru'
                emp.api_key_status='inactive'
                emp.api_key_end_date_0 = '12.12.2016'
                emp.api_key_end_date_1 = '14:12:05'
                emp.api_requests_available = 0
                emp.turnover =  0
                emp.coef = 1.40
                emp.save()
                self.stdout.write(
                    'Created distributor {}'.format(emp.name)
                )

Then I run this script on the server:
../../../manage.py import_csv "/home/webuser/fcprj/media/destributor.csv"

And the following is output:
Traceback (most recent call last):
  File "../../../manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/webuser/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/home/webuser/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/webuser/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/webuser/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "/home/webuser/fcprj/fcapp/management/commands/import_csv.py", line 19, in handle
    emp.address = row[1]
IndexError: list index out of range

I took an example of a script from the first answer
https://stackoverflow.com/questions/38820787/loadi...
The file itself was checked, there are all 5 columns that are used in the program.
5c55b478d6c99047549629.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question