MultiValueDictKeyError

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}")

It’s always helpful when you can post the complete traceback message and not just the summary line.

MultiValueDictKeyError at /admin/website/account/upload_accounts_csv/
'upload_accounts_csv'
Request Method:	POST
Request URL:	http://localhost:8000/admin/website/account/upload_accounts_csv/
Django Version:	4.1.7
Exception Type:	MultiValueDictKeyError
Exception Value:	
'upload_accounts_csv'
Exception Location:	G:\Projects\AccLedger\venv\lib\site-packages\django\utils\datastructures.py, line 86, in __getitem__
Raised during:	website.admin.upload_accounts_csv
Python Executable:	G:\Projects\AccLedger\venv\Scripts\python.exe
Python Version:	3.9.1
Python Path:	
['G:\\Projects\\AccLedger\\AccLedger',
 'C:\\Python39\\python39.zip',
 'C:\\Python39\\DLLs',
 'C:\\Python39\\lib',
 'C:\\Python39',
 'G:\\Projects\\AccLedger\\venv',
 'G:\\Projects\\AccLedger\\venv\\lib\\site-packages']
Server time:	Fri, 17 Mar 2023 02:05:40 +0000
Environment:


Request Method: POST
Request URL: http://localhost:8000/admin/website/account/upload_accounts_csv/

Django Version: 4.1.7
Python Version: 3.9.1
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'website']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "G:\Projects\AccLedger\venv\lib\site-packages\django\utils\datastructures.py", line 84, in __getitem__
    list_ = super().__getitem__(key)

During handling of the above exception ('upload_accounts_csv'), another exception occurred:
  File "G:\Projects\AccLedger\venv\lib\site-packages\django\core\handlers\exception.py", line 56, in inner
    response = get_response(request)
  File "G:\Projects\AccLedger\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "G:\Projects\AccLedger\AccLedger\website\admin.py", line 129, in upload_accounts_csv
    csv_file = request.FILES["upload_accounts_csv"]
  File "G:\Projects\AccLedger\venv\lib\site-packages\django\utils\datastructures.py", line 86, in __getitem__
    raise MultiValueDictKeyError(key)

Exception Type: MultiValueDictKeyError at /admin/website/account/upload_accounts_csv/
Exception Value: 'upload_accounts_csv'

And the form you’re using for the upload? (The form being rendered in upload_accounts_csv.html.)

In general, this error is going to be thrown when this line:

fails because that field doesn’t exist in the form being POSTed.

When in doubt, check the html that was rendered in the browser to verify that the name attribute of that field matches what you expected it to be.