Hi I am learning Django for a project and I am trying to upload a file along with a on option in dropdown list through a form using POST. Here are my files:
views.py
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
from .forms import UploadFileForm
# function to handle an uploaded file.
from save_uploaded_file import handle_uploaded_file
def index(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return render(request, 'viewer_app/display_image.html')
else:
print('error')
return render(request, 'viewer_app/index.html', {'form': form})
else:
return render(request, 'viewer_app/index.html')
forms.py
from django import forms
class UploadFileForm(forms.Form):
file = forms.FileField()
displayType = forms.ChoiceField(widget=forms.Select(), required=True)
save_uploaded_file.py
def handle_uploaded_file(f):
with open('static/viewer_app/temp.exr', 'wb+') as recieved_exr:
for chunk in f.chunks():
recieved_exr.write(chunk)
index.html
<div id="formDiv" style="display:none;" class="form" >
<form method="post" enctype="multipart/form-data" class="form-style">
<label for="browse">Upload file</label>
<input type="file" value="Browse" id="brow" /><br></br>
<label for="display">Display type</label>
<select id="display-type" name="display">
<option id="RGB1" value="RGB1">RGB1</option>
<option id="RGB2" value="RGB2">RGB2</option>
<option id="RGB3" value="RGB3">RGB3</option>
<option id="RGB4" value="RGB4">RGB4</option>
</select><br></br>
<input type="submit" value="Show file" id="showimage"/><br></br>
{% csrf_token %}
</form>
</div>
So, after I run the server to display the page and I select the upload and click submit, it doesn't upload and save the file and in the terminal I see the "error" text in the terminal which is displayed due to from.is_valid() not being true.
I tried to add {{ form.errors }} {{ form.non_field_errors }}
to the html file but I still don't know exactly what is that I am doing wrong.
- displayType
- This field is required.
- file
- This field is required.
[07/Aug/2017 22:07:25] "POST /viewer_app/ HTTP/1.1" 200 4467 – programmingIsFun Aug 07 '17 at 22:08