Why won't newly installed Django app with NGIN

2019-09-07 07:09发布

问题:

I have a Mac running OS X 10.9.3. I am trying to setup a Django application backed by a PostgreSQL database served by gunicorn, with static assets served by NGINX. I'm an old hand at Django with MySQL running with the developement server (manage.py runserver). But I'm new to setting it up with virtualenv, gunicorn and NGINX. So I'm following the instructions here.

My Django Project is being served successfully at http://localhost:3026. As a test of the database connectivity, I wanted to take a look at the Django Admin interface. I visited http://localhost:3026/admin/. I have included a screenshot below.

Why does this admin page look so ugly? It lacks the neccessary graphical interface and css that it is supposed to have? It looks like NGINX is not properly serving up those static assets. How can I troubleshoot and fix this issue?

I even did python manage.py collectstatic. That went and successfully copied all the static files to where they were supposed to (I think?) live in /opt/myenv/static. You can see the output of that command here. I then re-started gunicorn and nginx. I thought that would fix it. But unfortunately it didn't. The issue remains. In my Django settings.py file, I have configured the STATIC variables as follows:

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'djangobower.finders.BowerFinder',
)
STATIC_ROOT = "/opt/myenv/static/"
STATIC_URL = '/static/'

回答1:

Static files are only served by Django when the debug server is being used. When the site is being handled by a separate web server you need to configure the web server to serve the static files itself.



回答2:

Actually, it is recommended to use Django's own development server(python manage.py runserver) while you are on localhost(from my years' experience with Django and virtualenv). Since it save your precious time configuring the nginx locally.

However, if you do want to use Nginx to serve you static files locally, you may want to copy django's contrib **/admin static file directory to where your virtualenv points to**. Your virtualenv file(like a *.nginx file) of nginx will look like this:

 server_name  localhost;

 location /static {
     alias /path/to/where/your/admin/static/directory/is;
     autoindex on;
     access_log off; #optional
  }

Then restart nginx you probably will get it working. PS: for more about installing and configuring Nginx locally on a Mac, you may want to check this out.