Gunicorn with Django giving a problem with static files

三世轮回 提交于 2020-08-24 04:51:43

问题


Got a Django project named django_server. When I run

python manage.py runserver

the page shows up as expected

Then, if I run

gunicorn django_server.wsgi:application --bind 0.0.0.0:8000

The page shows without styling

Checking the console, can see the following errors for both .css and .js files

The resource from “http://0.0.0.0:8000/static/....css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).

In the terminal where the gunicorn command was executed, can read

NOT FOUND: /static/rest_framework/css/bootstrap.min.css
NOT FOUND: /static/rest_framework/css/bootstrap-tweaks.min.css
...

In settings.py I mention

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

This is the folder structure

Checked the permissions in static folder (ls -l)and they show as

drwxrwxr-x 4 tiago tiago 4096 jun 2 15:49 static

Checking the permissions in the files where the problem happens and

Added also to settings.py

import mimetypes

mimetypes.add_type("text/css",".css",True)
mimetypes.add_type("text/javascript",".js",True)

But the error remains.


回答1:


You need to run python manage.py collectstatic.


On your settings.py I recommend you to use whitenoise to serve your files.


1) pip install whitenoise


2) Add STATICFILES_STORAGE on settings.py

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'


3) Add to your MIDDLEWARE on settings.py

`MIDDLEWARE = [

  'whitenoise.middleware.WhiteNoiseMiddleware',

  'django.middleware.security.SecurityMiddleware',
  ...

]


来源:https://stackoverflow.com/questions/62155878/gunicorn-with-django-giving-a-problem-with-static-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!