I have created an app named customer within a project named Website using django. I have created a csv upload in the admin area which is connected to the Postgres db.
JavaScript
x
4
1
An error occurs when I upload the CSV returning:
2
Exception Type: IndexError
3
Exception Value: list index out of range
4
However the CSV file is still added to the db but the error screen is displayed. Even more strangely if I a notepad doc as csv containing the data and upload that I get no error until I try to upload a second data set. If I save an excel doc as csv I get the error. Where am I going wrong ?
JavaScript
1
148
148
1
Models.py
2
class customer(models.Model):
3
name = models.CharField(max_length=50, blank=True)
4
balance = models.CharField(max_length=120, blank=True)
5
6
def __str__(self):
7
return self.name
8
9
Admin.py
10
from django.contrib import admin
11
from django.urls import path
12
from django.shortcuts import render, redirect
13
from .models import customer
14
from django import forms
15
from django.contrib import messages
16
from django.http import HttpResponseRedirect
17
from django.urls import reverse
18
from import_export import resources
19
20
21
class data(resources.ModelResource):
22
23
class Meta:
24
model = customer
25
26
27
class CsvImportForm(forms.Form):
28
csv_upload = forms.FileField()
29
30
31
class CustomerAdmin(admin.ModelAdmin):
32
list_display = ('name', 'balance',)
33
34
def get_urls(self):
35
urls = super().get_urls()
36
new_urls = [path('upload-csv/', self.upload_csv), ]
37
return new_urls + urls
38
39
40
41
42
43
def upload_csv(self, request):
44
45
if request.method == "POST":
46
print("action is POST")
47
csv_file = request.FILES["csv_upload"]
48
49
if not csv_file.name.endswith('.csv'):
50
messages.warning(request, 'The wrong file type was uploaded')
51
return HttpResponseRedirect(request.path_info)
52
53
file_data = csv_file.read().decode("utf-8")
54
csv_data = file_data.split("n")
55
56
for x in csv_data:
57
fields = x.split(",")
58
created = customer.objects.update_or_create(
59
name=fields[0],
60
balance=fields[1],
61
)
62
63
64
65
form = CsvImportForm()
66
data = {"form": form}
67
return render(request, "admin/search/csv_upload.html", data)
68
69
70
71
72
admin.site.register(customer, CustomerAdmin)
73
74
75
76
csv_upload.html
77
{% extends 'admin/index.html' %}
78
79
{% block content %}
80
<div>
81
<form action ="." method="POST" enctype="multipart/form-data">
82
{{ form.as_p }}
83
{% csrf_token %}
84
<h1>Hello World upload files here to db</h1>
85
<button type="submit">Upload file</button>
86
</form>
87
</div>
88
{% endblock %}
89
90
91
change_list.html
92
{% extends 'admin/change_list.html' %}
93
94
{% load static %}
95
96
{% block content %}
97
98
<br><br>
99
<a href="upload-csv/">Upload a csv file</a>
100
<br><br><br>
101
102
<!-- Gives us all the other elements ont he page we want to access. -->
103
{{ block.super }}
104
105
{% endblock %}
106
107
108
Traceback error:
109
Environment:
110
111
112
Request Method: POST
113
Request URL: http://127.0.0.1:8000/admin/search/customer/upload-csv/
114
115
Django Version: 4.0.5
116
Python Version: 3.9.2
117
Installed Applications:
118
['django.contrib.admin',
119
'django.contrib.auth',
120
'django.contrib.contenttypes',
121
'django.contrib.sessions',
122
'django.contrib.messages',
123
'django.contrib.staticfiles',
124
'search',
125
'django.contrib.postgres',
126
'import_export']
127
Installed Middleware:
128
['django.middleware.security.SecurityMiddleware',
129
'django.contrib.sessions.middleware.SessionMiddleware',
130
'django.middleware.common.CommonMiddleware',
131
'django.middleware.csrf.CsrfViewMiddleware',
132
'django.contrib.auth.middleware.AuthenticationMiddleware',
133
'django.contrib.messages.middleware.MessageMiddleware',
134
'django.middleware.clickjacking.XFrameOptionsMiddleware']
135
136
137
138
Traceback (most recent call last):
139
File "C:UsersacartDesktopNew foldervenvlibsite-packagesdjangocorehandlersexception.py", line 55, in inner
140
response = get_response(request)
141
File "C:UsersacartDesktopNew foldervenvlibsite-packagesdjangocorehandlersbase.py", line 197, in _get_response
142
response = wrapped_callback(request, *callback_args, **callback_kwargs)
143
File "C:UsersacartDesktopNew folderwebsitesearchadmin.py", line 51, in upload_csv
144
balance=fields[1],
145
146
Exception Type: IndexError at /admin/search/customer/upload-csv/
147
Exception Value: list index out of range
148
Advertisement
Answer
Due to the nature of csv, you need to check if the length of your
field
item is 2.
i.e.
JavaScript
1
8
1
for x in csv_data:
2
fields = x.split(",")
3
if len(fields) == 2:
4
created = customer.objects.update_or_create(
5
name=fields[0],
6
balance=fields[1],
7
)
8
This way, you skip processing lines which are empty. Note that I’m assuming your expected field lengths is 2.