Search code examples
djangogitpython-3.xnginxwebserver

Django cant find static files on server, but works fine on local machine


I have a vps running with django, i'm developing the site from my local machine, and pushing it up to the vps by git.

On my local machine i've just installed the initializr, and changed all scripts to use the static location, and everything works fine there, but when i push it to my vps, all it finds is the .html files, it cant find either .css or .js scripts the vps is running Debian 8.* Minimal, with nginx, and gunicorn My local machine is running MacOs Both machines runs Python 3.6.2, and Django 1.11.4

Here are the relevant settings from settings.py:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
...
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "BaseFiles/templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
...
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "BaseFiles/static"),
)

My paths are:

Project_folder/ -> BaseFiles  |  Django_project | manage.py
BaseFiles/ -> static  |  templates

UPDATE Okay so it turns out, that if i run django manually from the vps, it loads the css and js files fine, so the problem is isolated to Nginx

Nginx:

server {
        listen 80;
        server_name domaine.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/user/project_folder;
    }

So it turns out i had a misconfiguration in my nginx site file. After adding the below after project_folder it worked fine

/BaseFiles

Solution

  • Try this:

    Give a static root to in your settings.py

    STATIC_ROOT = '/var/www/project/static/'
    

    And in your nginx:

    location /static/ {
        alias /var/www/project/static/;
    }
    

    Do python3 manage.py collectstatic and sudo service nginx restart and this should probably work. Hope this helps. Thanks.