Problem uploading file with Django


I just started working with Django 1.11. I am trying to upload a file using a form. I leave some samples of my code below.

First my form in

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50, label='Titulo')
    file = forms.FileField(label='Archivo')

The view in

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            return HttpResponseRedirect('/prueba/resultado/')
        form = UploadFileForm()
    return render(request, 'calendarioTest/formulario.html', {'form': form})

def resultado(request):
    var = 'Muchas gracias'
    return render(request, 'calendarioTest/resultado.html', {'var':var})

In the routes of my application I have:

urlpatterns = [
    url(r'^prueba/', include('calendarioTest.urls')),

urlpatterns = [
    url(r'^exportar/',views.CalendarioTest, name='exportar'),
    url(r'^formulario/', views.upload_file, name = 'formulario'),
    url(r'^resultado/', views.resultado, name='resultado'),

And the form template is as follows:

<form action="/prueba/formulario/" method="post">
    {% csrf_token %}
{{ form }}
<input type="submit" value="Submit">

However, when I select the file and put the title instead of redirecting to the page that I specify, it tells me that I have not selected any file. Activate the debug and when I get to the% part of% co tells me that the form is invalid, and on the page of my browser I can see the title written but the field of the file tells me that you have not selected any file.

This bothers me, because when the form only had fields such as title, name or email, the form was valid and redirected me to the specified page.

Could you tell me what I'm doing wrong in this case? Looking for a solution I found this: link but the answer did not help me , the form is still invalid and in the browser I still see the error that no file has been selected.

Greetings and thanks in advance.

asked by Ethan 26.05.2017 в 17:29

1 answer


When you work with files in your form you have to specify the enctype="multipart/form-data" attribute:

<form action="/prueba/formulario/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">

This is specified in the Django documentation for Basic file uploads :


Note that request.FILES will only contain data if the request was POST and the that posted the request has the attribute enctype="multipart / form-data". Otherwise, request.FILES will be empty.

That is, request.FILES will only contain information from your files as long as you have used the enctype="multipart/form-data" attribute. That's why you get the error.

answered by 26.05.2017 / 17:32