Django - Save file to static directory from view
Question: I am building a website with Django, hosted on PythonAnywhere. One of the
website pages is a private page that I use to build content that will be then
displayed in the public pages. Rather than saving the content produced within
the private page to the database and then retrieving it from the database, I
would like to save it to static files, in my static directory (it's a small
number of JSON files that will be served over and over again, so I think it
makes sense to serve them as static files).

In the view that defines my private page I have the following code for saving
the file:

    
    
    json=request.POST.get('json')
    name=request.POST.get('name')
    file=open(settings.STATIC_ROOT+'/'+name+'.json','w')
    file.write(json)
    file.close()
    

Note that I previously imported the settings:

    
    
    from django.conf import settings
    

Strangely, this worked for a while, but then it stopped working. The error I
get is:

    
    
    Exception Value: 'function' object has no attribute 'STATIC_ROOT'
    

Am I doing something wrong? Is the fact that I am on PythonAnywhere relevant?
Is it possible that the app is served by a worker that is not able to write to
my static directory? What can I do to solve the problem?


Answer: As pointed out by PythonAnywhere staff, the procedure was legitimate and
supposed to work because the app is served by a worker running as my own user
ID which has permissions to write to the static directory. The problem was
generated by a naming conflict due to the fact that also one of the views had
been named settings. To solve the problem I substituted the import statement
with

    
    
    from django.conf import settings as djangoSettings
    

and the open statement with

    
    
    file=open(djangoSettings.STATIC_ROOT+'/game'+name+'.json','w')
    

After doing these substitutions, everything seemed to work.

