I can't get Django admin css loaded using nginx server

February 8, 2016 4.4k views
Django Nginx Ubuntu

Hi I am trying to serve statics using Django and Nginx on a VPS to get my project live. My settings.py includes following.

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/
STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')

My project folder includes:
static
----static
----media
----templates

In Nginx I got following:

upstream gunicorn_server {
  # fail_timeout=0 means we always retry an upstream even if it failed
  # to return a good HTTP response (in case the Unicorn master nukes a
  # single worker for timing out).
  server 127.0.0.1:9000 fail_timeout=0;
}

server {

    listen   80;
    server_name example.com;
    keepalive_timeout 5;
    client_max_body_size 4G;

    access_log /home/projectuser/logs/nginx-access.log;
    error_log /home/projectuser/logs/nginx-error.log;

    location /static/ {
        alias   /venv/project/static/static;
    }

    location /media/ {
        alias   /venv/project/static/media;
    }
    location / {

        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;

        if (!-f $request_filename) {
            proxy_pass http://gunicorn_server;
            break;
        }
    }

}

I can't serve static no matter what and admin panel css is not showing up.

Please advise asap.

1 comment
  • Try looking into the collectstatic command line function in the Django documentation. Deploying a Django app in prod is much less simple than on localhost. But you will need to run collectstatic to grab your static files once the app is deployed; how exactly you do that is going to depend on your setup.

2 Answers

Thanks for help but it was the path issue in Nginx.

I had the same issue, my css was working for my actual site but not the admin page. To solve this follow the steps:
1) go to your command (e.g. puTTy, nginx) and type: nano /etc/nginx/sites-available/django
2) it will show you three file directories for media, static and admin static
2.5) quit the nano window by pressing ctrl X, don't save any changes made (in case you accidentally made a change)
3) for admin static make sure the static file is in the directory shown, if not ,copy paste the admin static files found in .......\Python2.7\Lib\site-packages\django\contrib\admin\static\admin

It should sort it out.

The problem is caused because it is looking for the static files of admin in the wrong place - so just put those files where its looking for it.

Have another answer? Share your knowledge.