D
D
Dima Zherebko2016-05-20 23:28:26
Django
Dima Zherebko, 2016-05-20 23:28:26

Django how to set up the return of images from local storage?

How can I make the server return an image when requesting the /static/file.png route?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
metajiji, 2016-05-21
@G_tost

It remains only to bring the default nginx config 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 scheme to work, you need to add to settings.py :
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'public', 'static')

With this configuration, the web server looks into the /srv/app/public/ directory and will first try to return what the user requested from disk, if it does not find it, it will send a request to Django.
And it also becomes possible to add your own static files to this directory (for example, a zip archive or a pdf document), in addition, there is no need to change anything in the nginx configuration, which is very convenient.
For media, you can do the same, if authorization is not provided for downloading media, for this you need to add to 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, then you should not put the media directory in public, in this case it is better to stick to the standard configuration:
STATIC_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'media')

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

I would also recommend setting up X-Accel-Redirect to serve media through nginx, but I won’t write about this in this post.

I
iegor, 2016-05-21
@iegor

https://docs.djangoproject.com/en/1.9/howto/static...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question