We are trying to read a csv file using view.py in pythonanywhere.com host. We want to get three cells (id, statement, and paragraph) from each row in the 1.csv file until last one.
The code is:
def home(request):
Stats = Statments.objects.all()
__file__ = '1.csv'
module_dir = os.path.dirname(__file__) # get current directory
file_name = os.path.join(module_dir, 'Politi_Stat/1.csv')
#Load statments to database from CSV
with open(file_name,"r", encoding = 'utf-8') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
book = Statments(id = row[0] ,statment=row[1], Paragraph=row[2])
book.save()
d = deque(posts)
d.extendleft(reversed(Stats))
We import the csv and os. It seems an encoding problem of the unicode UTF-8 of csv.
The output of the site is: Server 500
The output from the log file is:
Traceback (most recent call last):
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/fattoh/Politi_Stat/app/views.py", line 46, in home
for row in csv_reader:
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 82: invalid start byte
2019-11-27 19:20:54,714: Internal Server Error: /
Traceback (most recent call last):
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/fattoh/Politi_Stat/app/views.py", line 46, in home
for row in csv_reader:
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)