Django how to set out images from local storage?

Wish that when you request a route /static/file.png the server gave a picture ?
July 9th 19 at 12:40
2 answers
July 9th 19 at 12:42
Solution
Just need to give the default configuration of nginx for Django:
server {
 listen 80;
 server_name domain.ltd;
 root /srv/app/public;

 # Logs.
 access_log /var/log/nginx/domain.ltd_access.log;
 error_log /var/log/nginx/domain.ltd_error.log;

 # Options.
 client_max_body_size 0;
 keepalive_timeout 5;

 # Locations.
 location / {
 try_files $uri @proxy_to_app;
}

 location @proxy_to_app {
 proxy_pass http://127.0.0.1:8001; # See guniconf.py file.
 proxy_set_header Host $http_host;
 proxy_set_header X-Real-IP $remote_addr;
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_set_header X-Forwarded-Proto $scheme;
 "proxy_redirect" off;
}
}


In this case, it will be convenient to organize the project as follows:
/srv/app/
├── example
│ ├── forms.py
│ ├── __init__.py
│ ├── migrations
│ ├── models.py
│ ├── settings.py
│ ├── static
│ ├── templates
│ ├── urls.py
│ ├── views.py
│ └── wsgi.py
├── logs
├── manage.py
├── public
│ └── static
├── README.md
├── requirements.txt
└── venv


For this project you need to add in settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'public', 'static')


In this configuration, the web server looks in the directory /srv/app/public/ will try to first give a disk that the user requested, if not found, it will send the request to Django.
And there is the opportunity to put your own static files in this directory (e.g. zip archive or pdf document) in addition, there is no need to change something in your nginx configuration, which is very convenient.

For media can do the same if for download media not provided authorization to do this, add in settings.py:
STATIC_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'public', 'media')

/srv/app/
├── example
├── logs
├── public
│ ├── media
│ └── static
└── manage.py


If you still need authorization, you should not put the catalog in the public media, in this case it is better to stick with the standard configuration:
STATIC_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'media')

/srv/app/
├── example
├── logs
├── media
├── public
│ └── static
└── manage.py

Still would recommend to set X-Accel-Redirect to return media through nginx, but this is what I in this post I will not write.
July 9th 19 at 12:44

Find more questions by tags DjangoPython