I built a form with a FileField in order to upload file to be processed. Strangely it seem that file is closed before I can do anything with in the view. I encounter a ValueError after validating the form:
"I/O operation on closed file"
I can see that file is properly detected but closed when attempting to read it.
Note: Django version 2.2.25.
forms.py
class FileImportForm(forms.Form):
headers = ["lastname","firstname","gender","title","entity","email","company","address","phone"]
file = forms.FileField(label='CSV file',validators=[CsvFileValidator(headers)])
def clean_file(self):
file = self.cleaned_data['file']
return file
views.py
@login_required
def file_import(request):
if request.method == 'POST':
form = FileImportForm(request.POST,request.FILES)
if form.is_valid():
if request.FILES['file']:
file_post = request.FILES['file']
# Offending line below (I/O operation on closed file)
file_content = file_post.read().decode('UTF-8')
return redirect("/foo")
else:
form = FileImportForm()
return render(request,"file_import.html", { 'form': form })
How to properly process uploaded file (read, etc..)?