How to use handle_uploaded_file in Django

1

Hello, I'm using handle_uploaded_file in Django and it throws me the following error: MultiValueDictKeyError at / restore / "'file'"

Here I leave my code to see if you can help me and know what happens

This is the form.py :

class  Seleccion(forms.Form):
    selec= forms.FileField()

This is the view.py :

def restaurar(request):
    if request.method == 'POST':
        form = forms.Seleccion(request.POST, request.FILES)
        handle_uploaded_file(request.FILES['file'])
        return render(request, 'index.html')
    else:
        form = forms.Seleccion()
        return render(request, 'salvas.html', {'form': form})

def handle_uploaded_file(f):
    with open('upload_salva.sql', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
    
asked by Grace 12.12.2017 в 16:27
source

2 answers

0

The request.FILES is a dictionary where each key or key is the name that was inserted in the HTML input. Maybe you have several files associated with the same name of the input. You have 3 options that come to mind:

1- Assign a single file to the input, or verify that there are not several inputs with the same attribute name .

2- You could iterate through the FILES dictionary:

for nombre, archivo in request.FILES.iteritems():
    #archivo2 = request.FILES[nombre] # Esto es lo mismo que contiene archivo
    handle_uploaded_file(archivo)

3- Or you could extract (and remove from the dictionary) an element:

file, value = request.FILES.popitem()
handle_uploaded_file(request.FILES[file]) # Notece que las comillas no van

I hope I have been helpful!

Greetings!

    
answered by 12.12.2017 в 16:58
0

Fiate in your form, the error is that your field is not called file if not selec therefore, is the name of the key that will be associated with the request.FILES

It would be enough if you did

handle_uploaded_file(request.FILES.get('selec'))

I hope it's helpful

    
answered by 12.12.2017 в 21:16