Search code examples
pythondjangofile-permissions

django manage.py script messed up directory permissions


I have a script that checks a json file and downloads photos to a folder.

This bit checks if the directory exists and if not, creates it:

folder = media_root + 'photos/' + now.strftime('%Y') + '/' + now.strftime('%m') + '/' + now.strftime('%d')

if not os.path.isdir(folder):
    os.makedirs(folder)

everything worked like it should, but now the folder can't be written through the django admin interface, giving the error OSError: [Errno 13] Permission denied: media/photos/2014/08/31/OneOf.jpg

The only way this works is if I set the permissions to be writable by everyone. I checked and gunicorn is running with user nobody, and this never caused a problem before.

What could have caused this issue and how do I stop it from happening in the future?

EDIT:

I tried out the suggestions bellow but running the script as nobody only returned an error:

 File "./manage.py", line 8, in <module>
      from django.core.management import execute_from_command_line
 ImportError: No module named django.core.management

I also checked and the other folders, created by the django-admin interface, are also owned by root.

RESOLUTION:

the os.makedirs commands changed the whole directory tree to be owned by root, which is why that even with the same permissions as other folders django couldn't write to that directory.

To keep it from happening again the solution is to restore ownership to that directory tree once the new folder is created.


Solution

  • The problem is that you are running the script as root.

    The user that you run a program with is the same user that owns any files created by that program.

    Once you run a program as root, any output will also be owned by the root user, which means the user that is running the django app will not have access to those files.

    You should run the manage.py script as the same user that is running your web app (nobody) so that files created are then readable by the gunicorn process - and by extension, django.