Home > database >  request.FILES.get is empty in a Django project
request.FILES.get is empty in a Django project

Time:12-22

For a project I would like to use two files loaded by the user via two inputs, to apply an external script.

My problem is that I get an error because Django doesn’t seem to be able to locate these inputs. So I have an empty object instead of the file.

Here are my codes:

home.html

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
</head>
<body>
    <h1>Home</h1>
    <form action="/external/" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        Input xlsx file :<br><br>
        <input type="file" name="file1" accept=".xml" required><br>
        <input type="file" name="file2" accept=".xml" required><br>
 
        <input type="submit" value="Valider"><br>
    </form>
</body>
</html>

views.py

from django.shortcuts import render
from .scripts.extScript import *
 
def home(request):
    return render(request, 'home.html')
 
def external(request):
 
    f1=request.FILES.get('file1')
    f2=request.FILES.get('file2')
 
    extScript(f1,f2)
    return render(request,'home.html')

urls.py

from django.contrib import admin
from django.urls import include, path
from .views import *
 
urlpatterns=[
    path('',home,name="home"),
    path('external/',external, name="external")
]

architecture:

DjangoProject
   |
    -views.py
    -urls.py
    -scripts
        |
         -extScript.py  

templates
        |
         -home.html

and the error specifies that f1 type is < NoneType >

I want to point out that I tried to put f1=request.FILES[‘file1’] and it sends me that ‘file1’ is not found : raise MultiValueDictKeyError(key).

If anyone has an idea, I can’t solve this problem, I feel that everything is fine. Besides, I performed the same kind of function on another project and that works perfectly so I don’t know.

Thanks!

CodePudding user response:

That's because you are sending files with "POST" Request, which you should listen to on your views because first it start with GET view which don't have files. So the code must be like the following:

def external(request):
    if request.POST:
        f1=request.FILES.get('file1')
        f2=request.FILES.get('file2')
 
        extScript(f1,f2)
    return render(request,'home.html')

CodePudding user response:

I dont really know, but maybe you need to change the submit to a button <button type="submit">Upload</button> instead of <input>.

  • Related