Problem uploading file with Django

2

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 forms.py:

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

The view in views.py:

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            return HttpResponseRedirect('/prueba/resultado/')
    else:
        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'^admin/', admin.site.urls),
    url(r'^prueba/', include('calendarioTest.urls')),
]

calendarTest.urls.py

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">
</form>

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
source

1 answer

2

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">
</form>

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
source