Mustafa Hussien
Mustafa Hussien

Reputation: 31

django Static files in production server

My problem is with a static files (img , styles). My code is working fine with no error with static files and the images appears when I run the server, but when I make the (debug = False) the images and styles disappear I ran my code on Linux server ubuntu.... How do I make the static files appear with the (debug=false)?

in settings.py that is my code
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'music/templates/'),
)

In my html file the image-tag is just like this:

<img src="{% static 'music/login.jpg' %}" width="300" height="300">

Upvotes: 1

Views: 275

Answers (1)

ipeternella
ipeternella

Reputation: 93

As Jon Clements commented, if debug=False then the Django app staticfiles is disabled. Usually in production one uses a dedicated web server (a server that is not running Django to serve static files). Hence, to solve your problem, an extra server should be set up to serve the static files.

Some high level steps:

  1. Go to your django settings file and add a STATIC_ROOT which will be the directory where Django will place the static files;

  2. Run python manage.py collecstatic for Django to collect all the static files and put them at the STATIC_ROOT directory;

  3. Serve the files in this directory when a request contains your STATIC_URL in the URL (these requests will usually contain /static/ or something). For example, this can be done with an Nginx server or an Apache one as explained in Django docs:

https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/modwsgi/#serving-files

In terms of an Nginx config, one short snippet, just to illustrate such idea, could be something like:

server {

        listen 80;

        # hey Nginx, once you see something like /static/ in the url
        # try to grab the file that is under the alias directory and
        # return to the user
        location /static/myapp/ {
            alias /var/www/myproject/static/myproject/myapp/;
            access_log true;
            add_header Cache-Control "max-age=120";
        }
}

To sum things up:

Django's staticfiles app is great for local development but is not really suitable for production apps.

Hence, serving static files should usually be done by a dedicated and separated server such as Nginx or an Apache one which requires some additional configuration to set these servers up.

Upvotes: 1

Related Questions