我试图部署一个Django应用程序,在本地工作,但没有在我的网站。显示了Django index.html(模板),但显示了以下错误,并且没有加载css/js。
Failed to load resource: the server responded with a status of 404 (Not Found) - http://example.com/static/js/main
Failed to load resource: the server responded with a status of 404 (Not Found) - http://example.com/static/css/style.css
我认为与设置相关的行。py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'src.pages'
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'pages/static'),
]
如何在index.html模板中包含文件
{% load static %}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/>
</head>
<body>
<script src="{% static 'js/main.js' %}"></script>
</body>
</html>
应用程序结构如下
web_app/
├── src/
│ ├── config/
│ │ └── settings.py
│ ├── pages/
│ │ ├── static/
│ │ │ ├── css/
│ │ │ │ └── style.css
│ │ │ ├── js/
│ │ │ │ └── main.js
│ │ │ └── fonts/
│ │ ├── templates/
│ │ │ └── pages/
│ │ │ └── index.html
│ │ ├── urls.py
│ │ └── views.py
│ └── static (generated with collectstatic)/
│ ├── admin
│ ├── css/
│ │ └── style.css
│ ├── js/
│ │ └── main.js
│ └── fonts
├── manage.py
└── requirements.txt
尝试将JS代码移动到index.html中,它工作了,所以我猜它无法找到静态文件,因为某种原因。
我也试过设置css文件的绝对路径,但它给出了相同的错误。
Django不会提供静态文件,只有开发服务器(runserver)被配置为这样做,你要么让静态文件从Django前面的HTTP服务器(例如Apache2或Nginx)提供,这是推荐的方法,或者使用whitenouse