Why are media files not being loading

Viewed 50

I'm writting a web site which has api backend part and frontend part. I do not write a frontend part. And frontend is heavily tested and should be work fine. So the problem is with my backend. Media files are being loaded in docker container (checked) but are not being loaded in website (localhost). I have no 404's. It looks like there is no requests to media files on website.

global urls:

if settings.DEBUG:
    urlpatterns += static(
        settings.MEDIA_URL, document_root=settings.MEDIA_ROOT
    )

settings:

MEDIA_URL = '/media_backend/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'backend_media')

nginx:

server {
    listen 80;
    server_name 127.0.0.1;
    location /static_backend/ {
        alias /app/backend_static/;
    }
    location /static/admin {
        alias /app/backend_static/admin/;
    }
    location /media_backend/ {
        alias /app/backend_media/;
    }
    location /api/docs/ {
        root /usr/share/nginx/html;
        try_files $uri $uri/redoc.html;
    }
    location /api/ {
        proxy_pass http://backend:8000;
    }
    location /admin/ {
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Url-Scheme $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass   http://backend:8000/admin/;
    }
    location / {
        root /usr/share/nginx/html;
    }
}

docker-compose:

version: '3.8'
services:
  db:
    image: postgres:12
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    env_file:
      - ./.env
  backend:
    image: konstantin05/foodgram_backend:latest
    expose:
      - 8000
    restart: always
    volumes:
      - static_value:/app/backend_static/
      - media_value:/app/backend_media/
    env_file:
      - ./.env
  nginx:
    image: nginx:1.21.3-alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf
      - ../frontend/build:/usr/share/nginx/html/
      - ../docs/redoc.html:/usr/share/nginx/html/api/docs/redoc.html
      - ../docs/openapi-schema.yml:/usr/share/nginx/html/api/docs/openapi-schema.yml
      - static_value:/app/backend_static/
      - media_value:/app/backend_media/
    restart: always
    depends_on:
      - frontend
    frontend:
      image: konstantin05/foodgram_frontend:latest
      volumes:
        - ../frontend/:/app/result_build/
volumes:
  static_value:
  media_value:
  postgres_data:
1 Answers

instead of this:

volumes:
      - static_value:/app/backend_static/
      - media_value:/app/backend_media/

do this and try:

volumes:
      - static-value:/app/web
      - media-value:/app/web

And in your setting file add this:

MEDIA_ROOT = '/app/web/media'
STATIC_ROOT = '/app/web/static'

Because, you are adding forward slash at the end. This will solve the problem

Related