I'm trying to understand how static files are served up by Django using a 
project I've created on my Mac using Django 3, Gunicorn, and Nginx.  The 
website serves up templates correctly except that the templates can't see 
my CSS stylesheet.  When I go to a page, for example 
```127.0.0.1:8000/app1/``` and view the source, I see this in my HTML 
template:

    <link rel="stylesheet" href="/static/css/main.css">

If I click on the href link, I get a page "Not Found" at the address 
```http://127.0.0.1:8000/static/css/main.css```.  This seems like it should 
be the correct link but the template can't see the main.css stylesheet as I 
would expect.

Here are the relevant files in my 'mysite' project located in 
/Users/me/projects/django/django-staticfiles:

├── app1
│   ├── templates
│   │   └── app1
│   │       └── index.html
├── mysite
│   ├── settings.py
│   └── wsgi.py
├── static
│   └── css
│       └── main.css
├── static-final
│   ├── admin
│   │   ├── css
│   │   ├── fonts
│   │   ├── img
│   │   └── js
│   └── css
│       └── main.css

Here are the relevant settings:

# mysite/settings.py
...
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', ]
...
INSTALLED_APPS = [
    'django.contrib.staticfiles',
    'app1',
]
...
STATIC_URL = '/static/'
STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static-final/')
...

I installed Gunicorn into my virtual environment and run it with this 
command:

gunicorn --bind 0.0.0.0:8000 mysite.wsgi

I installed Nginx using Homebrew.  Here is the part of nginx.conf that 
includes my Nginx settings:

# /usr/local/etc/nginx.conf
...
http {
    ...
    server {
        listen      8080;
        server_name localhost;
    }
    ...
    include server/*;
}

Here is my Nginx configuration:

# /usr/local/etc/nginx/servers/django-staticfiles
server {
    listen 80;
    server_name 127.0.0.1;

    location / {
        proxy_pass http://127.0.0.1:8000;
    }

    location /static/ {
        alias /Users/me/projects/django/django-staticfiles/static-final/;
    }
}

I should add that when I stop Gunicorn and start Django's development 
server with DEBUG = True, the app1 template accesses the main.css file 
correctly.  It just can't see it when I'm running Gunicorn and Nginx.  I 
realize that I don't have a real need to run Gunicorn/Nginx on my Mac, but 
I've just set it up so I can compare and contrast how Django manages static 
files in development versus production.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/75f129a6-2dbf-47cc-b4ea-08008b30b047%40googlegroups.com.

Reply via email to