﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
27777	File object does not consistently open itself in context manager use	Raphael Gaschignard	Ingo Klöcker	"Django's {{{File}}} object has an open method that will reseek the file to 0,  and re-open the file if necessary (after closure).

Unfortunately, the context manager does not automatically open a file. In particular, {{{FieldFile}}} relies on implicit opening via the file property to open a file, but caches the object internally. Since the context manager for {{{File}}} closes the file after use, this means that using the context manager twice in a row fails (since the file is not re-opened).

{{{

class C(Model):
    pdf = FileField(...)

c = C.objects.get()

with c.pdf as pdf: # file not opened yet
     print(c.size) # pdf.size accesses pdf.file, which will implicitly open the file
# file is closed at the end of a context manager

 with c.pdf as pdf:
    print(c.size) # pdf.size now uses cached file, which is already closed!
}}}


I think it makes sense to have the context manager({{{__enter__}}}) call {{{open}}} on the object, so that files can be used in multiple context managers without having to to an open-ness check.

our current workaround is to check for closed-ness on all context manager uses:
{{{

with c.pdf as pdf:
     if pdf.closed():
         pdf.open() # seeks the file to 0 and opens if necessary
     # do ""real"" work

}}}


"	Cleanup/optimization	closed	File uploads/storage	1.10	Normal	fixed			Accepted	1	0	0	0	0	0
