Can’t see the forest through the trees. I have the same type of code working for another file import and thought how hard could it be to repeat?
I can’t find where the error below is caused any help is appreciated.
MultiValueDictKeyError at /admin/website/account/upload_accounts_csv/
admin.py
@admin.register(Account)
class AccountAdmin(admin.ModelAdmin):
list_display = (
'player_account',
'season',
'first_name',
'last_name',
'address',
'city',
'province',
'postal_Code',
)
list_filter = ('player_account', 'first_name',)
ordering = ('player_account',)
search_fields = ('last_name',)
# for the CSV upload
def get_urls(self):
urls = super().get_urls()
new_urls = [path('upload_accounts_csv/', self.upload_accounts_csv),]
return new_urls + urls
# CSV Upload
def upload_accounts_csv(self, request):
if request.method == "POST":
csv_file = request.FILES["upload_accounts_csv"]
if not csv_file.name.endswith('.csv'):
messages.warning(request, 'Error, CSV File required.')
return HttpResponseRedirect(request.path_info)
# Using Pandas to clean the file.
df = pd.read_csv(csv_file)
print(df)
items = Account.objects.all()
print(items)
# CSV to DB model mapping names in CSV must match model.
# @ Add a data checking routine.
for ind, row in df.iterrows():
created = Account.objects.update_or_create(
player_account = row['Player Account'],
season = row['Season'],
last_name = row['Last Name'],
first_name = row['First Name'],
address = row['Address'],
city = row['City'],
province = row['Province'],
postal_Code = row['Postal Code'],
)
url = reverse('admin:index')
return HttpResponseRedirect(url)
# CsvImportForm() added above
form = CsvImportForm()
data = {"form": form}
return render(request, 'admin/upload_accounts_csv.html', data)
upload_accounts_csv.html
{% extends "admin/base.html" %}
{% block content %}
<div>
<form action="." method="POST" enctype="multipart/form-data">
{{ form.as_p }}
{% csrf_token %}
<button type="submit">Upload File</button>
</form>
</div>
{% endblock %}
models.py
class Account(models.Model):
season = models.CharField(max_length=50)
player_account = models.CharField('Player Account', max_length=50, blank=True)
first_name = models.CharField(max_length=50, blank=True)
last_name = models.CharField(max_length=50, blank=True)
address = models.CharField(max_length=50, blank=True)
city = models.CharField(max_length=50, blank=True)
province = models.CharField(max_length=50, blank=True)
postal_Code = models.CharField(max_length=50, blank=True)
def __str__(self):
return(f"{self.player_account} {self.last_name}")