[Answered ]-Request.FILES.get is empty in a Django project

0👍

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')

1👍

For anyone who face same issue like this (also same problem like I faced before), following is the solution that works for me.

Let say you have at least this file structure in you Django project directory:

djangoproject
-- yourapp
   -- urls.py
   -- views.py
-- templates
   -- home.html

Thus, in your template (home.html), put this form part like this:

<html>
...
<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="fileobs1" accept=".xml, .csv" id="id_fileobs1">
    <input type="file" name="fileobs2" accept=".xml, .csv" id="id_fileobs2">
    <input type="submit" value="Execute">
</form>
...
</html>

Explanation: do not forget to put enctype="multipart/form-data" in form tag. In the input tag, you can add accept=".xml,.csv" just to limit the file extension that relate with your purpose.

Then, in your views.py, put this part like this (or similar like this):

from django.shortcuts import render

def compare(file1, file2):
    print ('compare: ', file1, file2)

def file_upload(request):
    if request.method == 'POST':
        file1 = request.FILES.get('fileobs1')
        file2 = request.FILES.get('fileobs2')
        compare(file1, file2)

    return render(request, "home.html")

Explanation: The function compare is just example of your external function. The function file_upload also works if you don’t want to check POST method.

Note: This solution works well in Django 4.0

0👍

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

0👍

When you send request from client, you need to send POST request if file it’s the case.

Leave a comment