0
votes

I made an input on the HTML File and the HTML code is

<form method="post" enctype="multipart/form-data">
{%csrf_token%}
  <div class="row justify-content-center">
    <input type="file" name="document"/>
  </div>
  <br/><br/>
  <center>
    <input type="submit" value="Upload file" />
  </center>
</form>

and my views.py is

if request.method == 'POST':

    uploaded_file = request.FILES['document']
    fs = FileSystemStorage()
    file_exist = request.POST.get('document')
    fs.save(uploaded_file.name, uploaded_file)
    # --- my another stuff ---
else:
    return render(request, 'index.html')

I made a code like that and when running a server that is no problem until I click the submit button by not choose any file (no file is chosen) and I have got an error

MultiValueDictKeyError at /creative/ 'document' Request Method: POST Request URL: http://127.0.0.1:8000/creative/ Django Version: 2.2.12 Exception Type: MultiValueDictKeyError Exception Value:
'document' Exception Location: C:\Users\User\Envs\pp\lib\site-packages\django\utils\datastructures.py in getitem, line 80 Python Executable: C:\Users\User\Envs\pp\Scripts\python.exe Python Version: 3.5.5 Python Path:
['C:\Users\User\Desktop\crrnt wrk\Perfect Pitch\PerfectPitch', 'C:\Users\User\Envs\pp\Scripts\python35.zip', 'c:\programdata\anaconda3\DLLs', 'c:\programdata\anaconda3\lib', 'c:\programdata\anaconda3', 'C:\Users\User\Envs\pp', 'C:\Users\User\Envs\pp\lib\site-packages'] Server time: Tue, 19 May 2020 08:55:22 +0000

so how should I solve this problem? Thank you all for your help.

1

1 Answers

0
votes

I had the same Problem:D I just use the Try-Except Block. Maybe this can help you

    if request.method == 'POST':
        try:
              uploaded_file = request.FILES['document']
              fs = FileSystemStorage()
              file_exist = request.POST.get('document')
              fs.save(uploaded_file.name, uploaded_file)
              # --- my another stuff ---

        except Exception:
           #use pass or a logger info or something else

So now, if u press the submit button ur programm will not crash and if u input a file, everything works fine too. Hope this can help u!