Django seems to want me to learn a whole new way of reading and writing files. It’s confusing, and while I’m sure it’s useful in some cases, I don’t need it. I’m trying to use the following more familiar Python mechanism:
with open('target-file', 'w') as f:
f.write( "Hello.\n" )
When I use that in the REPL it works fine: a file called “target-file” is created in the current working directory, containing the text “Hello.” But if I try to do that from inside a Django view, it creates the file, but does not write any text into it.
Why doesn’t it work? Is there anything I can do so that it will?
Actually, I’m personally surprised that it’s even creating the files. It’s not that Django wants you to do anything different - it’s that what you think your current directory is may not be what it really is.
Keep in mind that your “current directory” when you’re running a Django app is not the directory in which the module resides. Most often, permissions is going to be the issue.
First thing I would try would be to try to write the file in a specified directory with permissions explicitly granted to the account running your application. (’/tmp’ is probably a good place to try.)
Thanks again, Ken! It works now!
Your hunch was my hunch too, so I made sure (before making this post) to print the working directory to the view, and I gave that directory maximally permissive settings with chmod +777
.
I broke the code somehow in the course of trying to send to /tmp
like you suggested, and after putting it back together it works now. Unfortunately I didn’t commit any of the intermediate stages so I guess I won’t know what went wrong.
Here’s the code:
def index ( request ):
wd = os . getcwd ()
now = datetime . now () . timestamp()
with open( "/home/appuser/" + str ( now ),
'w' ) as f:
f . write( "Hello?\n" )
return render (
request,
'run_make/index.html',
{ "wd" : wd,
"now" : now } )