Reputation: 3938
This must be kind of basic issue but I am very new in Djnago and trying to learn how the forms work. I have looked in different sites and forums but I haven't managed to understand what I am doing wrong.
This is my form:
class UploadCSVForm(forms.Form):
csv_file = forms.FileField()
Its a very simple form used in order to upload a CSV file.
This is what I have in my view:
def layer_create(request, template='layers/layer_create.html'):
if request.method == 'POST':
form = UploadCSVForm(request.POST, request.FILES)
#print form.is_bound # THIS PRINTS TRUE
#print (request.FILES['csv']) # THIS PRINTS THE FILE IN THE MEMORY
if form.is_valid():
print ("valid")
else:
print ("not valid")
out = {'success': False}
return HttpResponse('test site')
And this is the form in my Template:
<form id="file-uploader" method="post" enctype="multipart/form-data" action="{% url "layer_create" %}">
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
<input type="file" id="file-input" name="csv" />
<button type="submit" id="upload-button" class="btn btn-danger">Upload</button>
</form>
Using the function is_bound
I see that there are actual data bound on the form.
And when I print: request.FILES['csv']
I can see the name of the file uploaded in the Memory.
But I still get form.is_valid = False
without ant errors or warnings.
Upvotes: 0
Views: 675
Reputation: 600041
You've named the field in the template csv
, but the form is expecting it to be called csv_file
.
Generally you should let Django output the fields in the template, which will avoid issues like this. (It will also normally prepopulate the fields when redisplaying them after errors, although this doesn't happen for file fields for browser security reasons.)
{{ form.csv_file }}
Upvotes: 2