skip to Main Content

I am trying to write a file to the django media folder, but on execution I get a permission denied error. The configuration works fine on the OSX development platform, but not on the Ubuntu test server.

I have the following config:

settings.py

    
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
    MEDIA_URL = '/media/'
    print('SETTINGS CWD = ', os.getcwd())

models.py methods:

    def template_to_file(self):
        print('MODELS CWD = ', os.getcwd())
        with open(path + '/newsletter-volume-1.html', 'w') as static_file:
            static_file.write('Hello')
    
    def save(self, *args, **kwargs):
        self.template_to_file()
        super(Newsletter, self).save(*args, **kwargs)

On the OSX development platform the file writes to the media folder and the Current Working Directory prints are as follows:

SETTINGS CWD = /Users/tb/Documents/dev/backoffice

MODELS CWD = /Users/tb/Documents/dev/backoffice

However, on the Ubuntu platform I get:

[Errno 13] Permission denied: ‘/home/admin/backoffice/media/newsletter-volume-1.html’

SETTINGS CWD = /home/admin/backoffice

MODELS CWD = /

The following permissions are set as follows (admin is the owner of Django):

drwxrwxr-x 9 admin admin 4096 Jun 19 09:05 .
drwxr-xr-x 7 admin admin 4096 Jun 19 06:02 ..
drwxrwxr-x 2 admin admin 4096 Jun 19 06:07 media

admin@ubuntu:~/backoffice$ ps aux | grep django
admin      12606  0.4  6.6  82028 62280 ?        S    09:05   0:25 /home/admin/backoffice/venv/bin/python /home/admin/backoffice/venv/bin/celery -A backoffice beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler
admin      18686  0.0  0.0   7692   684 pts/0    S+   10:35   0:00 grep --color=auto django

Apache runs Django via WSGI

sudo ps aux | grep apache
[sudo] password for admin:
root       13921  0.0  0.5  14188  4924 ?        Ss   09:24   0:00 /usr/sbin/apache2 -k start
www-data   13922  0.1  6.6 407752 61752 ?        Sl   09:24   0:06 /usr/sbin/apache2 -k start
www-data   13923  0.0  1.2 2008496 12072 ?       Sl   09:24   0:00 /usr/sbin/apache2 -k start
www-data   13924  0.0  1.2 2008480 11844 ?       Sl   09:24   0:00 /usr/sbin/apache2 -k start
admin      20310  0.0  0.0   7692   684 pts/0    S+   10:58   0:00 grep --color=auto apache

I have tried this in shell on the Ubuntu test server and it works fine.

Does anyone have a solution to this and an explanation as to why the Current working directory changes to ‘/’ on the Ubuntu server?

2

Answers


  1. Permission denied is fair as you created files by root and serving by Apache, just give ownership to ‘www-data’ using chown and it will work

    Login or Signup to reply.
  2. This error occurs when the file that are trying to write is opened already. To avoid the error just create the code to close the file before you write it/on it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search