PermissionError at /xxx/yyy/ [Errno 13] Permission denied: '/..../media/profile_images/xxx.jpg'

created at Feb. 26, 2021, 6:18 p.m.

BUG

After finishing deployment of my django blog, I found there is a problem with uploading images.

To fix this problem, two steps could be checked at least

  1. MEDIAL_ROOT (nginx.conf \<---> settings.py)
  2. the privileges of the perform user of our django project

#1 MEDIA_ROOT problem

in deployment I use nginx as proxy, so if you use nginx too, you should gurantee the MEDIA_ROOT in settings.py is the same as the media path asigned in nginx.conf.

for example, in my nginx.conf configuration of media path is:

location /media/ {
            root   /home/My_Porject/My_App;  # tell nginx where "media" directory locates
        }

then I would change  MEDIA_ROOT in settings.py from development version:

MEDIA_ROOT = str(APPS_DIR / "media")

to absolute path:

MEDIA_ROOT = "/home/My_Porject/My_App/media/"

reference

#2 User Privileges

after reading some articles, I noticed that there must be some problem with the privileges of the user I used to run my Django project

if you have the same problem, just do as follows:

check the owner of your project

cd /home/my_project

check the owner of my_project, in my case, it's under the /home directory. You may see somthing like below:

drwx------ 3 admin    admin    4096 Feb 26 17:40 admin
drwxr-xr-x 7 root     root     4096 Feb 27 00:01 My_Project
drwx--x--x 6 My_User  My_User  4096 Feb 27 04:50 My_User

note that the owner of the My_Project is root rather than My_User (the perform user), so this is the problem.

further on, we may cd into My_Project to see files and directories owned by which user:

cd My_Project && ll


drwxr-xr-x  4 root root 4096 Feb 26 22:37 config
drwxr-xr-x  2 root root 4096 Feb 27 01:12 deploy
drwxr-xr-x  2 root root 4096 Feb 27 00:26 logs
-rw-r--r--  1 root root 1037 Feb 26 19:09 manage.py
drwxr-xr-x  2 root root 4096 Feb 26 19:00 requirements
drwxr-xr-x 17 root root 4096 Feb 26 22:37 My_app

change the owner from root to user

its very easy to do this:

[root@localhost ~]$ cd /home
[root@localhost home]$ su - My_User
[My_User@localhost ~]$ cd /home
[My_User@localhost home]$ sudo chown -R username:group directory
  • username:group: should be replaced with your own USERNAME and its GROUP, in my case, it's My_User:My_User
  • sudo chown -R username:group directory:will change ownership (both user and group) of all files and directories inside of directory and directory itself.
  • sudo chown username:group directory: will only change the permission of the folder directory but will leave the files and folders inside the directory alone. (reference)

after doing this, the owner of your project would be changed.

last: restart your project and you will find it works.

Please log in to leave a comment.