Django : Media file not found when deleting despite it's correctly written when creating (PROD)

I've been searching in vain for a long time the origin of this issue.

Everything works well on development : csv file upload + deletion but in production, file is well uploaded when saving my model but it's not found when I want to delete it.

views.py (file_name = sources/newone/egr-2022-light_copie.csv)

os.remove(f"media/{str(flow.fl_file_name)}")

settings.py. (custom settings file for prod)

BASE_DIR = Path(__file__).resolve().parent.parent
[...]
MEDIA_ROOT = '/home/django/httpdocs/gsm2/media'
MEDIA_URL = '/media/'

apache conf (+ssl)

[...] 
Alias /static /home/django/httpdocs/gsm2/static
<Directory /home/django/httpdocs/gsm2/static>
        Require all granted
</Directory>

Alias /media /home/django/httpdocs/gsm2/media
<Directory /home/django/httpdocs/gsm2/media>
        Require all granted
</Directory>

<Directory /home/django/httpdocs/gsm2/gsm2>
[...]

I have tried to :

  • modify the path used in remove() by removing media/... without success.
  • modify the path used in remove() by adding gsm2/in front of media/ ... uselessly.
  • to replace my settings.py media path with MEDIA_ROOT = os.path.join(BASE_DIR, 'media')... not better
  • Changed folder rights to 777 and ownership to 'django' ... in vain

Any idea about the possible origins of my pains ?

Found a workaround using @Naushad solution

Replaced :

os.remove(f"media/{str(flow.fl_file_name)}")

with :

file = os.path.join(os.path.dirname(os.path.dirname(__file__)), 
   f"media/{str(flow.fl_file_name)}")
os.remove(file)

Still have to analyse this solution for a good understanding.

Back to Top